lcm in c
/* a & b are the numbers whose LCM is to be found */
int lcm(int a,int b)
{
int n;
for(n=1;;n++)
{
if(n%a == 0 && n%b == 0)
return n;
}
}
For GCD:
Code:
/* a & b are the numbers whose GCD is to be found.
Given a > b
*/
int gcd(int a,int b)
{
int c;
while(1)
{
c = a%b;
if(c==0)
return b;
a = b;
b = c;
}
}
10-06-2005, 03:51 AM #2
shabbir
Go4Expert Founder
Join Date: Jul 2004
Location: On Earth
Posts: 11,740
Thanks: 41
Thanked 212 Times in 167 Posts
Rep Power: 10
Re: Finding LCM & GCD in C
For LCM
Code:
if(n%a == 0 && n%b == 0)
shouldn't this be
Code:
if(a%n == 0 && b%n == 0)
Also just another way to write the loop
Code:
for(n=1;;n++)
{
if(n%a == 0 && n%b == 0)
return n;
}
can be
Code:
for(n=1;a%n == 0 && b%n == 0;n++);
return n
For GCD Given a > b can be avoided if we have the following code
Code:
int gcd(int a,int b)
{
int c;
if(a
No comments:
Post a Comment