Monday, 10 October 2011

GCD of two numbers in C


Method 1:


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,d,r=0,LCM,m,n;
clrscr();
printf("Enter the two numbers : ");
scanf("%d %d",&a,&b);
m=a;
n=b;
/*if(a>b)
{
c=b;
b=a;
a=c;
}
else
goto loop;
loop:
*/
do
{
r=b%a;
d=a;
a=r;
b=d;
}while(r!=0);
LCM=(m*n)/d;
printf("\n\nLCM= %d",LCM);
printf("\n\nGCD is= %d",d);
getch();
}


Method 2:

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,i=0;
clrscr();
printf("Enter the two numbers :");
scanf("%d %d",&a,&b);
if(a<b)
for(i=a;i>=1;i--)
{
if(a%i==0 && b%i==0)
{
printf(" %d ",i);
break;
}
}
if(b<a)
for(i=0;i>=1;i--)
{
if(a%i==0 && b%i==0)
{
printf(" %d ",i);
break;
}
}
getch();
}

Method 3:


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter the two numbers: ");
scanf("%d %d",&a,&b);
m:
if(b==0)
{
printf("gcd is=%d",a);
goto n;
}
if(a>b)
{
a=a-b;
goto m;
}
else
{
b=b-a;
goto m;
}
n:
getch();
}



Method 4:
#include<stdio.h>
#include<conio.h>
int gcd(int a,int b)
{
  return (b==0)?a:gcd(b,a%b);
}
void main()
{
  int a,b;
  clrscr();
  printf("Enter the two numbers: ");
  scanf("%d %d",&a,&b);
  printf("gcd= %d ",gcd(a,b));
  getch();
}

No comments:

Post a Comment