Greatest Common Divisor ( GCD ) or Highest Common Factor ( HCF ) or Greatest Common Factor ( GCF ) of two numbers is the greatest positive integer that perfectly divides both the numbers. You can find more about GCD of two numbers on Wikipedia. In this tutorial, I will show you a very simple way to find GCD of two numbers using C language.
You can also find GCD of two numbers using Euclid’s Method in C language which is explained here.
Algorithm:
- Let
aandbbe the two numbers whose GCD you want to find. - Let
tempbe any temporary number, initially set to the bigger number amongaandb. - Check whether
tempperfectly divides bothaandbor not. - If it is, then
tempis the GCD ofaandb, otherwise move to step 5. - Increment the value of
tempand move to step 3.
Instructions:
- Use only the following header file in C program.
#include <stdio.h> - In
main, ask the user to input two numbers whose GCD he/she wants to find.
int a,b, temp; printf("Enter two numbers whose GCD you want to find : "); scanf("%d%d", &a, &b); - Find the GCD of these two numbers
aandbusing the user defined functionfindGCDwhich will return GCD of these two number and print its value.
temp = findGCD(a, b); printf("GCD of %d and %d is %d", a, b, temp); - In
findGCDfunction, define a temporary variablegcdand assign it value of the smaller number amongaandb(i.e. if a > b then gcd = b, otherwise gcd = a). No using a while loop which will run untillgcdperfectly divides bothaandb, and increment the value ofgcdin this loop. And finally return the value of variablegcd.
int findGCD(int a, int b) { int gcd = a > b ? b : a; while(a % gcd != 0 || b % gcd != 0) { gcd--; } return gcd; }
Here are some screenshots of sample programs.
You can download the sample code from here.

