Header Ads Widget

C program to find GCD of two numbers

Algorithm:-

                   1)  Find minimum (m)  between both numbers .

                   2)   take a variable (i ) initialize  it by 1 and a another variable G.

                    3) Repeat step 4 and 5 while i is less than or equal to minimum number (m).

                    4)  check if i is divided both numbers than update G=i.

                    5)  increase value of i by 1.

Code:-

#include<stdio.h>

// function for gcd
int gcd(int a ,int b)
{
int c,g;
c=a>b?b:a; // find minimum between both numbers
for(int i=1;i<=c;i++)
{
if(a%i==0 && b%i==0)
g=i;
}
return g;
}
int main()
{
int x,y,ans;
printf("Enter two numbers");
scanf("%d%d",&x,&y);
ans=gcd(x,y); // function calling
printf("GCD of %d and %d is %d",x,y,ans);
return 0;
}

Output:-


Enter two numbers 12 8
gcd of 12 and 8 is 4





                                                              

Post a Comment

2 Comments