Write an Object Oriented Program in C++, to find the GCD of two given numbers. 225 and 45
Write an Object Oriented Program in C++, to find the GCD of two given numbers.
Given numbers are 225 , 45
Write an Object Oriented Program in C++, to find the GCD of two given numbers.
Given numbers are 225 , 45
Best answer
#include <iostream>
using namespace std;
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
int main() {
int a = 225, b = 45;
cout<<"GCD of TWO NUMBERS"<< a <<" and "<< b <<" is "<< gcd(a, b);
return 0;
}
Answer: The GCD of 225 and 45 is 45. An object-oriented program puts the numbers and the GCD function inside a class.
#include <iostream>
using namespace std;
class GCD
{
int a, b;
public:
void getData(int x, int y)
{
a = x;
b = y;
}
int find()
{
int x = a, y = b, r;
while (y != 0)
{
r = x % y;
x = y;
y = r;
}
return x;
}
void display()
{
cout << "GCD of " << a << " and " << b
<< " is " << find() << endl;
}
};
int main()
{
GCD g;
g.getData(225, 45);
g.display();
return 0;
}How it works: the class GCD holds the two numbers as private data. find() uses Euclid's method: replace (x, y) by (y, x % y) until y becomes 0; then x is the GCD.
For 225 and 45: 225 % 45 = 0, so (x, y) becomes (45, 0) and the GCD is 45.
Output: GCD of 225 and 45 is 45
Log in or create a free account to answer this question.