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 gcd
function will always return 0
. Change
return y;
to
return x;
Understand the Euclid's algorithm:
RULE 1: gcd(x,0) = x
RULE 2: gcd(x,y) = gcd(y,x % y)
consider x = 12
and y = 18
gcd (12, 18)
= gcd (18, 12) Using rule 2
= gcd (12,6) Using rule 2
= gcd (6, 0) Using rule 1
= 6
As you can see when y
becomes zero x
will be the gcd
so you need to return x
and not y
.
Also while calculating lcm you are multiplying the numbers first which can cause overflow. Instead you can do:
lcm = x * (y / gcd(x,y))
but if lcm
cannot fit in an int
you'll have to make it long long
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
to return x
in gcd()
otherwise 0 will be returned everytime.
Problem 3) x * y
may overflow if x
and y
are large.
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 a long long
for that as well.
#include <iostream>
using namespace std;
long long gcd(long long int a, long long int b){
if(b==0)
return a;
return gcd(b,a%b);
}
long long lcm(long long a,long long b){
if(a>b)
return (a/gcd(a,b))*b;
else
return (b/gcd(a,b))*a;
}
int main(){
long long int a ,b ;
cin>>a>>b;
cout<<lcm(a,b)<<endl;
return 0;
}
This C program is different approach towards finding LCM
#include<stdio.h>
int main()
{
int a,b,lcm=1,i=2;
printf("Enter two numbers to find LCM\n" );
scanf("%d %d",&a ,&b);
while(i <= a*b)
{
if(a%i==0 & b%i==0)
{
lcm=lcm*i;
a=a/i;
b=b/i;
i=i-1;
}
if( a%i==0 & b%i!=0)
{
lcm=lcm*i;
a=a/i;
i=i-1;
}
if( b%i==0 & a%i!=0)
{
lcm=lcm*i;
b=b/i;
i=i-1;
}
i++;
}
printf("The LCM of numbers is %d\n", lcm);
}