C program : How to find HCF of two numbers
#include<stdio.h>
int main(){
int x,y,m,i;
printf("Insert any two number: ");
scanf("%d%d",&x,&y);
if(x>y)
m=y;
else
m=x;
for(i=m;i>=1;i--){
if(x%i==0&&y%i==0){
printf("\nHCF of two number is : %d",i) ;
break;
}
}
return 0;
}
Other logic : HCF (Highest common factor) program with two numbers in c
#include<stdio.h>
int main(){
int n1,n2;
printf("\nEnter two numbers:");
scanf("%d %d",&n1,&n2);
while(n1!=n2){
if(n1>=n2-1)
n1=n1-n2;
else
n2=n2-n1;
}
printf("\nGCD=%d",n1);
return 0;
}
--> HCF program with multiple numbers in c
#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;
}Output:
Post a Comment