Project Euler Problem 5: Smallest multiple

Smallest multiple

Problem 5

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?


C++:

#include <iostream>

using namespace std;

long gcd(long m, long n)
{
    for(;;) {
        if(n == 0)
            return m;
        long temp = m % n;
        m = n;
        n = temp;
    }
}

long lcm(long a, long b)
{
//    return a * b / gcd(a, b);
   return a / gcd(a, b) * b;

}

int main()
{
    long n, minans;

    while(cin >> n) {
        minans = 1;
        for(int i=2; i<=n; i++)
            minans = lcm(minans, i);

        cout << minans << endl;
    }

    return 0;
}



参考链接:计算最小共倍数LCM



posted on 2017-03-19 07:34  海岛Blog  阅读(138)  评论(0编辑  收藏  举报

导航