Write a C++ program using the concept of OOP to find the LCM of two numbers


Write a C++ program using the concept of OOP to find the LCM of two numbers.

Algorithm:

  1. Create a LCM class with private variables num1, num2 to store the two numbers for which LCM is to be calculated.
  2. Define a public method calculate() in the class to calculate the LCM of the two stored numbers by using the formula (num1 * num2) / GCD(num1, num2) and return the result.
  3. Define a private method GCD(int a, int b) in the class to calculate the GCD of the two numbers using the Euclidean algorithm.
  4. In the main() function, prompt the user to enter two numbers.
  5. Create a LCM object with the two numbers entered by the user.
  6. Call the calculate() method of the LCM object to find the LCM of the two numbers.
  7. Print the LCM of the two numbers.
  8. End the program.


Coding:

#include <iostream>
using namespace std;
 
class LCM {
  private:
    int num1, num2;
  public:
    LCM(int n1, int n2) {
      num1 = n1;
      num2 = n2;
    }
 
    int calculate() {
      return (num1 * num2) / GCD(num1, num2);
    }
 
    int GCD(int a, int b) {
      if (b == 0) {
        return a;
      }
      return GCD(b, a % b);
    }
};
 
int main() {
  int n1, n2;
 
  cout << "Enter first number: ";
  cin >> n1;
  cout << "Enter second number: ";
  cin >> n2;
 
  LCM lcm(n1, n2);
 
  cout << "LCM: " << lcm.calculate() << endl;
 
  return 0;
}
 
#OOP
#HappyProgramming
#HappyCoding

No comments:

Post a Comment