-1

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

  • Please [edit] your question and add the input you use, the output you get and the expected output. – Bodo Jan 21 '22 at 14:22
  • Because for inputs of “2” and “3” it prints “the lcm is 0”, which is wrong since the least common multiple of 2 and 3 is 6. To understand why it is wrong, you should step through the code, executing it yourself with pencil and paper to compute and track the values. Pay attention to the value of `c` as the loop progresses and how the values of `i` and `n` change. – Eric Postpischil Jan 21 '22 at 14:28
  • There are known efficient, simple and most importantly - correct algorithms for finding LCM (for example one using Euclid's GCD algorithm). Why not implement it? https://stackoverflow.com/questions/3154454/what-is-the-most-efficient-way-to-calculate-the-least-common-multiple-of-two-int/3154503 – Eugene Sh. Jan 21 '22 at 14:37

1 Answers1

0

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.

Guillaume Petitjean
  • 2,408
  • 1
  • 21
  • 47