我想要的输出是可以被 1 到 20 的所有数字整除的最小正值?

时间:2021-06-09 17:09:35

标签: java for-loop nested-loops

import java.util.*;
class Example {
    public static void main(String[] args){
        int smallest_positive_number,i,count,rem;
        
        count =0;
        for(smallest_positive_number=1;smallest_positive_number<2147483647; smallest_positive_number++){
            for(i=1; i<=20; i++){
                rem=smallest_positive_number%i;
                if(rem==0){
                    count++;
                }
            }
            if(count==20){
                System.out.print(smallest_positive_number+" is the smallest value that is evenly divisible by all the numbers from 1 to 20");
            }
            count=0;
            
        }
    }
}

我编写这段代码是为了找到可以被 1 到 20 之间的所有数字整除的最小正值。我找不到任何错误,也没有显示任何编译时错误。但它在运行时不提供任何输出。我想知道错误吗?

1 个答案:

答案 0 :(得分:0)

我不知道这是否有很大帮助,但是如果您在“System.out”之后添加“break”,它可以正常工作,但仍然很慢。

if(count==20){
                System.out.print(smallest_positive_number+" is the smallest value that is evenly divisible by all the numbers from 1 to 20");
                break;
            }

希望对大家有用。