-1

I have created a code for finding LCM of two nos. I think that the code is correct but I have an undesired output. What ks the problem in this code?

#include<stdio.h>
#include<conio.h>

main()
{
int i, j, a, b, lcm;

printf("Enter two nos : ");
scanf("%d %d", &a, &b);

for(i=1; i<=b; i++)
{
    for(j=1; j<=a; j++)
    {
        if(a*i==b*j)
        {
            lcm=a*i;
            break;
        }
    }
}
printf("LCM=%d", lcm);

getch();
}

1 Answers1

0

The LCM of two numbers a,b is at least max(a,b) and at most a*b, so your first idea about the boundaries is correct. But if you take a closer look to one of the definitions of LCM (of two positive integers) a and b you'll find that the LCM is the smallest number such that LCM % a = 0 and LCM % b = 0 where "%" means "remainder of integer division, truncating" and that is exactly what you can use here.

Example:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  int a, b, lcm;

  printf("Enter two nos : ");
  scanf("%d %d", &a, &b);

  /* TODO: checks and balances! */

  /* Set lcm to the larger of the two numbers */
  lcm = (a < b) ? b : a;

  /* check if both "a" and "b" divide "lcm" without a remainder
   * otherwise increment "lcm" */
  for (;;) {
    if ((lcm % a == 0) && (lcm % b == 0)) {
      /* we got the LCM, break out of loop */
      break;
    }
    /* Otherwise increment "lcm" by one */
    lcm++;
  }

  printf("LCM = %d\n", lcm);

  exit(EXIT_SUCCESS);
}

There are more elegant and more general methods but I think the example above is quite easy to follow.

deamentiaemundi
  • 5,502
  • 2
  • 12
  • 20