Write a C++ program using the concept of OOP to find the LCM of two numbers.
Algorithm:
- Create a LCM class with private variables num1, num2 to store the two numbers for which LCM is to be calculated.
- 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.
- Define a private method GCD(int a, int b) in the class to calculate the GCD of the two numbers using the Euclidean algorithm.
- In the main() function, prompt the user to enter two numbers.
- Create a LCM object with the two numbers entered by the user.
- Call the calculate() method of the LCM object to find the LCM of the two numbers.
- Print the LCM of the two numbers.
- 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