The code is running perfectly for finding LCM of 2 and 3 , LCM of 0 and 2 BUT not able to execute for (-2 and 3) or (-2 and -3). I have written code for this type. Check else if block that's the problem. I expect LCM of -2 and -3 to get printed as 6. And LCM of -2 and 3 to get printed as 6.
#include <stdio.h>
int main()
{
int a,b;
printf("\n\t\t\t\t\tThis program calculate LCM of two numbers");
printf("\nEnter two numbers: ");
scanf("%d%d",&a,&b);
int i=0;
if(a!=0 && b!=0)
{
if(a>0 && b>0)
{
for(i=1; i<=a*b; ++i)
{
if((i%a==0)&&(i%b==0))
break;
}//for loop end
printf("LCM is %d",i);
}
else if(a<0 || b<0) //if any one number is -ve or both are -ve
{
// while(1)
// {
// int max = (a > b) ? a : b;
// if ((max % a == 0) && (max % b == 0))
// {
// printf("The LCM of %d and %d is %d.", a, b, max);
// break;
// }
// ++max;
// }
//Above commented portion not working for -ve numbers. This is my issue.
}
}
else
{
printf("LCM is %d",i);
}
return 0;
}
Potential infinite loop
When
(max % a == 0) && (max % b == 0)is not true, loop goes on forever.Since OP wants a positive result, consider 1) using the absolute value of both arguments. 2) Use
long longmath to avoidintoverflow in the absolute value and ina*b.There are faster approaches than iterating
[1...a*b].