c - 求C中两个数的LCM

标签 c lcm

我创建了一个代码来查找两个编号的 LCM。我认为代码是正确的,但我有一个不需要的输出。这段代码有什么问题?

#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();
}

最佳答案

两个数字 a,b 的 LCM 至少为 max(a,b) 且至多为 a*b,因此您关于边界的第一个想法是正确的。但是,如果您仔细查看 LCM(两个正整数)a 和 b 的定义之一,您会发现 LCM 是满足 LCM % a = 0 和 LCM % b = 0 的最小数,其中“% "的意思是“整数除法的余数,截断”,这正是您可以在此处使用的。

示例:

#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);
}

还有更优雅、更通用的方法,但我认为上面的例子很容易理解。

关于c - 求C中两个数的LCM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52569815/

相关文章:

c - 为什么要在定义函数的过程中声明变量?

c++ - 计算 N 个数的 LCM 模 1000000007

c - 使用 ulimit -s unlimited 的段错误

javascript - 计算从 1 到 k 的 lcm(i, j)、i 和 j 之和的最有效方法是什么?

c++ - 使用模板计算 2 个数字的 LCM

python - 这个lcm python代码我做错了什么?

c - 执行异步 I/O 操作时退出

c - 一致的数组参数是 VLA 吗?

c - 为客户端收到的消息出现段错误