Issue in calculating LCM of two -ve numbers or if either one is negative in C lang

82 Views Asked by At

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;
}
1

There are 1 best solutions below

0
chux - Reinstate Monica On

Potential infinite loop

When (max % a == 0) && (max % b == 0) is not true, loop goes on forever.

// OP's code
while(1) {
  int max = (a > b) ? a : b;  // Did OP want this before the loop?
  if ((max % a == 0) && (max % b == 0)) {
    printf("The LCM of %d and %d is %d.", a, b, max);
    break;
  }
  ++max; // This line serves no purpose.
} 

Since OP wants a positive result, consider 1) using the absolute value of both arguments. 2) Use long long math to avoid int overflow in the absolute value and in a*b.

There are faster approaches than iterating [1...a*b].