以简单的方式在java中打印素数

时间:2016-01-11 23:30:59

标签: java

我想制作一个代码来打印所有素数..我在java中做了这个代码..我在isPrime方法的if语句中有问题,我不知道如何实现它..这里是代码

public class PrimeList {

    private boolean [] numbers;

    /** Creates a complete filled out, the prime list of the numbers from 1 to n */
    public PrimeList(int n) {

        numbers = new boolean [n];
    }
    /** Prints all primes found */
    public void printPrimeList() {
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<numbers.length; i++) {
        if(isPrime(i)==true) {
            sb.append(i +",");
        }
        }
        System.out.print(sb.toString());
        }

    /** Returns true if the NBR is a prime number that is listed,
    false in all other cases */
    public boolean isPrime(int nbr) { 
        if(nbr == 2) {
            return true;
        } else if (nbr/2 gives an int number && nbr/3 gives an int number ) {
            return false;
        } else {
            return true;
        }

    }

    public static void main(String[] args) {

        PrimeList primes = new PrimeList(100);
        primes.printPrimeList();

    }
}

当你看到这一行else if (nbr/2 gives an int number && nbr/3 gives an int number ) {时,我不知道如何实现它?

请帮我实现这个if语句..

谢谢:)

1 个答案:

答案 0 :(得分:2)

基本上你要做的是迭代所有整数x直到nbr的平方根并检查nbr / x的剩余部分是否为0

要获得除法运算的其余部分,必须使用模数运算符%

示例:

for (int i=2; i<=Math.sqrt(nbr); i++) {
    if (nbr % i == 0) {
        // we found a number that divides evenly into nbr without 
        // any remainder, therefore this number is not a prime.
        return false;
    }
} 
return true;

将它留作练习来弄清楚为什么你只需要迭代到平方根。

相关问题