Finding GCD of Array Code C language

Cod_Ubau picture Cod_Ubau · Jan 15, 2014 · Viewed 44.6k times · Source

I am trying to write a program in C. The program is supposed to find the GCD (greatest common divisor) of a given array. I am trying to use the smallest number of the array to find the GCD. I was wondering whats wrong with my last loop. I havent figured a way on how to check if the division is giving any decimal points in order to stop the loop. This is my code

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int A[10]={112, 160, 180, 240, 288, 32, 480, 96, 60, 72};
    int i;
    int j;
    int minimum = A[0];
    int GCD;
    int temp;

    for (i=1;i<9;i++)
    {
        if( A[i] < minimum)
        {
            minimum = A[i];
        }
    }

    for (i=1; i < minimum/2; i++)
    {
        for (j = 0; j < 9;j++)
        {
            GCD = 2*i;
            temp = ((A[j])/(GCD));
            int check = temp%1;
            if (check == 0)
                break;
        }
    }

    printf("The Greates Common Denominator is: %d", GCD);

    return 0;
}

Answer

BLUEPIXY picture BLUEPIXY · Jan 15, 2014
#include <stdio.h>

unsigned gcd(unsigned x, unsigned y){
    unsigned wk;
    if(x<y){ wk=x;x=y;y=wk; }
    while(y){
        wk = x%y;
        x=y;
        y=wk;
    }
    return x;
}

int gcd_a(int n, int a[n]){
    if(n==1) return a[0];
    if(n==2) return gcd(a[0], a[1]);
    int h = n / 2;
    return gcd(gcd_a(h, &a[0]), gcd_a(n - h, &a[h]));
}

int main(void){
    int A[10]={112, 160, 180, 240, 288, 32, 480, 96, 60, 72};
    int size_A = sizeof(A)/sizeof(*A);
    int gcd = gcd_a(size_A, A);
    printf("%d\n", gcd);
    return 0;
}