Find out the GCD of two numbers using while loop in C language

CServer Side ProgrammingProgramming

Problem

Generate the greatest common divisor for any two numbers using C programming language.

Solution

Let the user enter any two numbers from the console. For those two numbers, let’s find the greatest common divisor.

The GCD of two numbers is the largest number that exactly divides both of them without a remainder.

The logic we use to find the GCD of two numbers is as follows

while(b!=0) //check for b=0 condition because in a/b ,b should not equal to zero
{
rem=a % b;
a=b;
b=rem;
}
Print a

Program 1

Live Demo

#include<stdio.h>
int main(){
int a,b,rem;
printf("enter any two numbers:");
scanf("%d%d",&a,&b);
while(b!=0) //check for b=0 condition because in a/b ,b should not equal to zero{
rem=a % b;
a=b;
b=rem;
}
printf("GCD of two numbers is:%d\n",a);
return 0;
}

Output

enter any two numbers:8 12
GCD of two numbers is:4

Check: 8= 2 * 2 *2
12= 2 * 2 * 3

The Greatest common divisor of two numbers is : 2 * 2 =4

Program 2

In this example, let us find the GCD of two numbers using for loop −

Live Demo

#include <stdio.h>
int main(){
int num1, num2, i, GCD;
printf("enter two numbers: ");
scanf("%d %d", &num1, &num2);
for(i=1; i <= num1 && i <= num2; ++i){
if(num1%i==0 && num2%i==0)
GCD = i;
}
printf("GCD of two numbers is:%d", GCD);
return 0;
}

Output

enter two numbers: 24 48
GCD of two numbers is:24
Published on 05-Mar-2021 11:08:35