Search code examples
cgreatest-common-divisor

GCD logical error


I wrote this code to get the gcd in c. It works perfectly for small numbers but when I tried 60 and 90 for example I got 2, while getting 3 for 9 &6.

#include "stdio.h"
#include "stdlib.h"
int main()
{
    int a,b,x,gcd;
    printf("Please Enter the fraction");
    scanf("%d", &a);
    scanf("%d", &b);
    if(b%a == 0)
        gcd =a;
    else
    {
        x=a;
        while(--x>1)
        {
            if (a%x == 0 && b%x==0)
            {  
                 gcd =x;
            }
        }
    }
    printf("GCD = %d", gcd);
    return 0;
}

Solution

  • #include "stdio.h"
    #include "stdlib.h"
    int main()
    {
        int a,b,x,gcd;
        printf("Please Enter the fraction");
        scanf("%d", &a);
        scanf("%d", &b);
        if(b%a == 0)
            gcd =a;
        else
        {
            x=a;
            while(--x>1)
            {
                if (a%x == 0 && b%x==0){
                    gcd =x;
                    break;
                }
            }
        }
        printf("GCD = %d", gcd);
        return 0;
    }
    

    The problem is that when you find the gcd you must break the loop //Otherwise you can use this recursive function

    int gcd(int a, int b) {
        if ( a == 0 ) {
            return b;
        } else {
            return gcd(b%a, a);
        }
    }