Find the GCD of two numbers

Using For Loop

#include<stdio.h>
int main(){
    int x,y,m,i;
    do {
        printf("Enter two number: ");
        scanf("%d%d",&x,&y);
        if(x==0 || y==0)
          printf("Please check the input and try again...\n");
    } while(x==0 || y==0);
    if(x>y)
         m=y;
    else
         m=x;

    for(i=m;i>=1;i--){
         if(x%i==0&&y%i==0){
             printf("\nGCD of %d and %d is %d",x,y,i) ;
             break;
         }
    }
    return 0;
}

Using Recursion

#include <stdio.h>

int gcd(int a, int b)
{
    if (a == b)
        return a;
    if (a > b)
        return gcd(a-b, b);
    return gcd(a, b-a);
}

int main()
{
    int x,y,m,i;
    do {
        printf("Enter two number: ");
        scanf("%d%d",&x,&y);
        if(x==0 || y==0)
          printf("Please check the input and try again...\n");
    } while(x==0 || y==0);
    printf("GCD of %d and %d is %d ", x, y, gcd(x, y));
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *