java java的素数程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15618721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:16:41  来源:igfitidea点击:

Prime number program for java

javanumbersprimeslogic-programming

提问by idude

I'm new to programming and need help on a java program. I want my program to return all the prime numbers between 1 and 10.

我是编程新手,需要有关 Java 程序的帮助。我希望我的程序返回 1 到 10 之间的所有质数。

    for(int i=1; i<=10; i++){
        int factors = 0;
        int j=1;

        while(j<=i){
            if(i % j == 0){
                factors++;
            }
            j++;
        }
        if(factors==2){
            System.out.println(j);
        }
    }

Instead of receiving 2,3,5 and 7 I receive 3,4,6,and 8

我收到的不是 2、3、5 和 7,而是 3、4、6 和 8

回答by Veger

You print jinstead of i, change your println()line to:

您打印j而不是i,将您的println()行更改为:

System.out.println(i);

Your results are 'one too large' as j = i + 1after the while-loop.

j = i + 1while-loop之后,您的结果“太大了” 。

回答by padilo

just print i instead of j

只打印 i 而不是 j

for(int i=1; i<=10; i++){
    int factors = 0;
    int j=1;

    while(j<=i){
        if(i % j == 0){
            factors++;
        }
        j++;
    }
    if(factors==2){
        System.out.println(i);
    }
}