HCF program with multiple numbers in C

Posted By: Matpal - January 25, 2012
#include<stdio.h>
int main(){
    int x,y=-1;
    printf("Insert numbers. To exit insert zero: ");
   
    while(1){
         scanf("%d",&x);
         if(x<1)
             break;
         else if(y==-1)
             y=x;
         else if (x<y)
             y=gcd(x,y);
         else
             y=gcd(y,x);
    }

    printf("GCD is %d",y);
   
    return 0;
}

int gcd(int x,int y){
    int i;
    for(i=x;i>=1;i--){
         if(x%i==0&&y%i==0){
             break;
         }
    }
    return i;
}

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.