C ++算法计算多个数字的最小公倍数 [英] C++ algorithm to calculate least common multiple for multiple numbers

查看:106
本文介绍了C ++算法计算多个数字的最小公倍数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在C ++算法来计算多个数字的最小公倍数,例如 lcm(3,6,12) lcm(5 ,7,9,12)

Is there a C++ algorithm to calculate the least common multiple for multiple numbers, like lcm(3,6,12) or lcm(5,7,9,12)?

推荐答案

您可以使用std :: accumulate和一些帮助器功能:

You can use std::accumulate and some helper functions:

#include <iostream>
#include <numeric>

int gcd(int a, int b)
{
    for (;;)
    {
        if (a == 0) return b;
        b %= a;
        if (b == 0) return a;
        a %= b;
    }
}

int lcm(int a, int b)
{
    int temp = gcd(a, b);

    return temp ? (a / temp * b) : 0;
}

int main()
{
    int arr[] = { 5, 7, 9, 12 };

    int result = std::accumulate(arr, arr + 4, 1, lcm);

    std::cout << result << '\n';
}

这篇关于C ++算法计算多个数字的最小公倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆