博客
关于我
16.最小公倍数
阅读量:133 次
发布时间:2019-02-27

本文共 563 字,大约阅读时间需要 1 分钟。

为了求正整数A和B的最小公倍数,可以使用它们的最大公约数。通过公式:最小公倍数 = (A × B) / 最大公约数。我们可以使用辗转相除法来高效计算最大公约数。

方法1:暴力求解

虽然效率较低,但对于较小的数值来说是可行的。具体步骤如下:

  • 找到较大的数m。
  • 从m开始,逐个检查是否能被A和B整除。
  • 一旦找到满足条件的m,输出它作为最小公倍数。
  • 方法2:利用最大公约数

  • 使用辗转相除法计算A和B的最大公约数。
  • 应用公式计算最小公倍数:(A × B) / GCD(A, B)。
  • 代码实现

    #include 
    using namespace std;int gcd(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return a;}int main() { int a, b; while (cin >> a >> b) { cout << a * b / gcd(a, b) << endl; } return 0;}

    示例

    • 输入:5 7

    • 输出:35

    • 输入:4 6

    • 输出:12

    这种方法高效且准确,适用于所有正整数情况。

    转载地址:http://tpbb.baihongyu.com/

    你可能感兴趣的文章
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    nova基于ubs机制扩展scheduler-filter
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>