Write
program in C to Find GCD of two positive integers X and Y
Ans
#include <iostream>
|
using namespace std;
|
int gcd(int, int);
|
int GCD(int a, int B)/>;
|
|
int main()
|
{
|
int num1, num2;
|
|
//get two numbers
|
cout << "Please
enter two positive integers seperated by a comma: ";
|
cin >> num1
>> num2;
|
while ((num1 < 0) ||
(num2 < 0))
|
{
|
cout << "Please
enter two positive integers: ";
|
cin >>
num1 >> num2;
|
}
|
|
//Display GCD of two numbers.
|
cout << "The
greatest common divisor of "<< num1;
|
cout << "
and " << num2 << " is ";
|
cout << gcd(num1,
num2) << endl;
|
system("pause");
|
return 0;
|
}
|
|
// Recursive call to function
|
int gcd(int x, int y)
|
{
|
if (x % y == 0)
|
return y;
|
else
|
return gcd(y,
x % y);
|
}
|
|
|
// Iterative call to function
|
int GCD(int a, int B)/>
|
{
|
while (1)
|
{
|
a =
a % b;
|
if (
a == 0)
|
{
|
return b;
|
}
|
b =
b % a;
|
if (b
== 0)
|
{
|
return a;
|
}
|
}
|
}
|
No comments:
Post a Comment