Sunday, July 13, 2008

find the GCD and LCM of two integers

/* Write a C program to find the GCD and LCM of two integers *
* output the results along with the given integers. Use Euclids' algorithm*/

#include stdio.h
#include conio.h

void main()
{
int num1, num2, gcd, lcm, remainder, numerator, denominator;
clrscr();

printf("Enter two numbers\n");
scanf("%d %d", &num1,&num2);

if (num1 > num2)
{
numerator = num1;
denominator = num2;
}
else
{
numerator = num2;
denominator = num1;
}
remainder = num1 % num2;
while(remainder !=0)
{
numerator = denominator;
denominator = remainder;
remainder = numerator % denominator;
}
gcd = denominator;
lcm = num1 * num2 / gcd;
printf("GCD of %d and %d = %d \n", num1,num2,gcd);
printf("LCM of %d and %d = %d \n", num1,num2,lcm);
} /* End of main() */
/*------------------------
Output
RUN 1
Enter two numbers
5
15
GCD of 5 and 15 = 5
LCM of 5 and 15 = 15
------------------------------*/

This uses a Euclid's GCD (and LCM) algorithm. The discription is found here.

http://www.geocities.com/SiliconValley/Garage/3323/aat/a_eucl.html. Its better explained there. There is nothing much to tell about syntax.

No comments: