cwhile-looplcm

why can't this code be used to find the lcm of two numbers?


This is the code I wrote. Please tell me the mistakes and knowledge gap I may have

#include <stdio.h>
int main()
{  
   int i,n,c=1;
   printf("enter the number 1:");
   scanf("%d",&i);
   printf("enter the second number:");
   scanf("%d",&n);
   while (i!=n)
   {
    c++;
    i=i*c;
    n=n*c;
   }
   
   printf("the lcm is %d",i);  
   return 0;
}

Input I put: 2 & 3

The output I get: The lcm is 0

Output expected: The lcm is 6


Solution

  • Your algorithm is simply wrong.

    Take a basic example i=3 and n=4.

    The LCM is 12 and to get 12 you multiply both numbers by a different number. Whereas you're assuming that you need to multiply both numbers by the same factor c.

    You may have found the solution yourself by doing a very easy debugging step by step. You can even do that online for a basic code like yours.

    There are other issues in your code, like the fact your are using signed integer (you probably need unsigned integer instead) and the fact you are nottaking care about integer overflow.