C++ Program to find GCD

Last Updated:

What is Greatest Common Divisor?

A largest number that exactly divides two or more integers.

In general, Greatest Common Divisor (GCD) is otherwise called as Greatest Common Factor (GCF) or Highest Common Factor (HCF)

Tips: It is recommended to use our online GCD calculator for better understanding.

Examples

The following table provides few examples of GCD of the given numbers.

NumbersGCD
4, 10 2
6, 5 1
15, 30 , 45 15

GCD of Two Numbers

In the following example, we will find the GCD of the given two numbers (45, 90).

Example

C++ Compiler
#include <iostream> using namespace std; int main() { int num1 = 45; int num2 = 90; int gcd = 1; int i; for(i=2; i<=num1 && i <= num2; i++) { // Checks if i is factor of both integers if(num1 % i == 0 && num2 % i == 0) gcd = i; } cout << "GCD of " << num1 <<" and " << num2 <<": " << gcd; return 0; }

GCD of any Two Given Numbers

In the following example, we will find the GCD of any two given numbers.

Example

C++ Compiler
#include <iostream> using namespace std; int main() { int num1, num2, i; int gcd = 1; cout << "Enter (int) num1 = "; cin >> num1; cout << "Enter (int) num2 = "; cin >> num2; for(i=2; i<=num1 && i <= num2; i++) { // Checks if i is factor of both integers if(num1 % i == 0 && num2 % i == 0) gcd = i; } cout << "\nGCD of " << num1 <<" and " << num2 <<": " << gcd; return 0; }

Share this Page

Meet the Author