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.
Your
gcdfunction will always return0. Changeto
Understand the Euclid’s algorithm:
consider
x = 12andy = 18As you can see when
ybecomes zeroxwill be thegcdso you need to returnxand noty.Also while calculating lcm you are multiplying the numbers first which can cause overflow. Instead you can do:
but if
lcmcannot fit in anintyou’ll have to make itlong long