欧拉计划005--最小公倍数

欧拉计划005

Smallest multiple

\(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\)?

最小公倍数

\(2520\)是最小的能够被\(1\)\(10\)整除的数。

最小的能够被\(1\)\(20\)整除的正数是多少?

这道题用的方法也是枚举,主要是该怎么判断什么时候结束循环。如果需要判断的数很小,我们直接可以i%1==0&&i%2==0这样写,但是我们需要判断1-20的数,这样写很明显是不科学的,因此我们需要改变一下,我们用1-20的循环来判断是否符合条件。但是,我们该怎么判断退出循环的条件呢?在这里,我用了一个布尔型的变量flag来标记,在每次进入循环时,都将flag设置为true,在后续的判断条件中,如果不符合条件,那么我们则将flag设置为false。如果在多轮循环下来,我们的flag都为true,那个此时i就是最小的符合条件的数。这个数具体多大我也不知道,判断1-10时的时候,最小的数时2520,到我们这里,最小的数就变成了232792560。

答案:232792560。

#include <iostream>
using namespace std;

int main(){
    int min;
    bool flag;
    for(int i=1;i<2147483647;i++){
        flag = true;
        for(int j=1;j<=20;j++){
            if(i%j!=0){
                flag=false;
                break;
            }
        }
        if(flag==true){
            min = i;
            break;
        }
    }
    cout<<"最小的数是"<<min<<endl;
    return 0;
}
posted @ 2021-09-20 17:07  ChrisNg  阅读(106)  评论(0)    收藏  举报