检查 int 是否为素数 Java

Check if an int is prime Java

对不起 "fix my code" post

编辑:与 for 循环的语法相关而不是素数,现在也已解决。

我的任务是从控制台获取一个 int 并(在不同的行上)打印出从 1 到 n 的所有质数(包括 1 和 n)。 我的方法从 n 开始,检查它是否为素数,然后将 n 递增 1 并循环直到 n=2。 要检查一个数字是否为素数,我 运行 一个循环,检查是将数字除以 x 的余数等于零,x 从 2 开始并在 root(n) 处停止。 现在这一切在理论上都有效,并且阅读我的代码我看不出哪里出了问题。

public class Prime {
public static boolean isPrime(int n) {
    boolean result = true;
    for (int x = 2; x>=sqrt(n); x++) {
        if ((n % x) == 0) {
            result = false;
            break;
        } else {
            x++;
        }
    }
    return result;
}

public static void main(String[] args) {
    Scanner intIn = new Scanner(System.in);
    int i = intIn.nextInt();
    while (i>=2) {
        if (isPrime(i)) {
            System.out.println(i);
            i--;
        } else {
            i--;
        }
    }
  }
}

例如,输入 10 将 return 10(连同 9,8,7,6,5,3),即使 isPrime() 检查是否 10 % 2 == 0,然后设置result 为假。 我在这里错过了什么??

我再次为这个烦人的(稍微重复的)问题道歉。

for 循环中的条件是继续 循环的条件,而不是停止 的条件。您需要将 >= 替换为 <=:

for (int x = 2; x<=sqrt(n); x++) {
    // Here -----^

您将 x 递增两次,循环条件应为 x<=sqrt(n) :

for (int x = 2; x>=sqrt(n); x++) { // here
    if ((n % x) == 0) {
        result = false;
        break;
    } else {
        x++; // and here
    }
}

正确的逻辑应该是:

public static boolean isPrime(int n) {
    for (int x = 2; x<=sqrt(n); x++) {
        if ((n % x) == 0) {
            return false;
        }
    }
    return true;
}

循环中x必须小于等于 因此,将 (int x = 2; x>=sqrt(n); x++) 的表达式更改为 对于 (int x = 2; x<=sqrt(n); x++)

这样试试看,简洁明了多了

public static boolean isPrime(int candidate) {
        int candidateRoot = (int) Math.sqrt((double) candidate);
        return IntStream.rangeClosed(2, candidateRoot)
                .noneMatch(i -> candidate % i == 0); // return true if the candidate
                                                     // isn't divisible for any of the
                                                     // numbers in the stream
    }

    public static void main(String[] args) {
        Scanner intIn = new Scanner(System.in);
        int i = intIn.nextInt();

        List<Integer> primeList = IntStream.rangeClosed(2, i)
                .filter(candidate -> isPrime(candidate))
                .boxed()
                .collect(toList());
        System.out.println(primeList);

        // Another way
        Map<Boolean, List<Integer>> primeAndNotPrimeMap = IntStream.rangeClosed(2, i)
                .boxed()
                .collect(partitioningBy(candidate -> isPrime(candidate)));
        System.out.println(primeAndNotPrimeMap);


    }