I am getting wrong result for my LCM program.
Ifirst find gcd of the numbers and then divide the product with gcd.
int gcd(int x, int y)
{
while(y != 0)
{
int save = y;
y = x % y;
x = save;
}
return y;
}
int lcm(int x, int y)
{
int prod = x * y;
int Gcd = gcd(x,y);
int lcm = prod / Gcd;
return lcm;
}
Any help much appreciated.
You should return x instead of y in your gcd function.
Also, are you sure the product x*y will always fit into an
int
? Might be a good idea to use along long
for that as well.Problem 1)
int gcd = gcd(x,y);
gcd
is already defined to be a function. You cannot define a variable with the same name.Problem 2) Change
return y
toreturn x
ingcd()
otherwise 0 will be returned everytime.Problem 3)
x * y
may overflow ifx
andy
are large.This C program is different approach towards finding LCM
Your
gcd
function will always return0
. Changeto
Understand the Euclid's algorithm:
consider
x = 12
andy = 18
As you can see when
y
becomes zerox
will be thegcd
so you need to returnx
and noty
.Also while calculating lcm you are multiplying the numbers first which can cause overflow. Instead you can do:
but if
lcm
cannot fit in anint
you'll have to make itlong long