Code and analyse to compute the greatest common divisor (GCD) of two numbers.
Algorithm/Flowchart (For programming based labs):
• Step 1: Let a, b be the two numbers
• Step 2: a mod b = R
• Step 3: Let a = b and b = R
• Step 4: Repeat
• Steps 2 and 3 until a mod b is greater than 0
• Step 5: GCD = b
• Step 6: Finish
#include <iostream>
using namespace std;
int gcd(int a, int b)
{
int result = min(a, b);
while (result > 0)
{
if (a % result == 0 && b % result == 0)
{
break;
}
result--;
}
return result;
}
int main()
{
int a = 35, b = 45;
cout << "GCD of " << a << " and " << b << " is "
<< gcd(a, b);
return 0;
}
0 Comments