A Program to Calculate the GCD of Two Integers

In this example, we are giving a program to calculate the GCD(greatest common divisor) of given two integers.


Program to calculate the GCD:

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. int n1, n2, i, gcd;
  6. cout << "Enter two positive integers: ";
  7. cin >> n1 >> n2;
  8. for(i=1; i <= n1 && i <= n2; ++i)
  9. {
  10. if(n1%i==0 && n2%i==0)
  11. gcd = i;
  12. }
  13. cout << "GCD =" << gcd;
  14. return 0;
  15. }

Output:

Enter two positive integers: 49
7
GCD = 7