简体   繁体   English

NthPrime-while / for循环或if语句集有什么问题?

[英]NthPrime- what's wrong with this while/for loop or set of if-statements?

Having trouble understanding what's wrong in the code. 无法理解代码中的错误。

I'm also trying to avoid using multiple methods if possible and just keep the functionality within the while loop. 我还尝试尽可能避免使用多种方法,而只是将功能保留在while循环中。

public class NthPrime {
    public static void main(String[] args) {
        int n;
        System.out.println("Which nth prime number do you want?");
        n = IO.readInt();
        if(n <= 0) {
            IO.reportBadInput();
            return;
        }
        if(n == 1) {
            System.out.println("Nth prime number is: 2");
            return;
        }
        int primeCounter = 1;
        int currentNum = 3;
        int primeVal = 0;

        while(primeCounter < n) { 
            for(int x = 2; x < currentNum; x++) { 
                if(currentNum % x == 0) {
                    continue;
                } else {
                    primeVal = currentNum;
                    primeCounter++; 
                }
            }
            currentNum++;
        }
        System.out.println(primeVal);
    }
}

Your code assumes that every time it encounters a number coprime to the number it's checking, it has a prime. 您的代码假定每次遇到要检查的数字的互质数时,它都有一个质数。 That is to say, your if block: 也就是说,您的if块:

if(currentNum % x == 0) {
    continue;
} else {
    primeVal = currentNum;
    primeCounter++; 
}

says "If it's composite (ie divisble by x ), then there's no point in continuing to test this number. However , if it's not composite, then we have a prime!" 说:“如果它是合成的(即,被x整除),则没有必要继续测试该数字。 但是 ,如果它不是合成的,那么我们就有质数!” This is faulty because if there's a composite number above the coprime number, your code doesn't care. 这是有问题的,因为如果在互质数上方有一个复合数,则您的代码不在乎。

This faulty test also gets run for every single coprime number below the number you're checking. 对于每个低于您要检查的互质数的故障,该错误测试也会运行。

You may be able to fix this by moving the code that updates primeVal and increments primeCounter to the place where you're certain that currentNum is prime. 您可以通过将更新primeVal并递增primeCounter的代码primeVal 确定 currentNum为质数的位置来解决此问题。 This would be after the for loop is done checking all the numbers below currentNum . 这将在for循环完成之后检查currentNum以下的所有数字。

General hint: Speed up your code by looping to the square root of currentNum , not currentNum itself. 一般提示:通过循环到currentNum平方根(而不是currentNum本身)来加速代码。 It's equivalent to what you have now, but faster. 它相当于您现在所拥有的,但是更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM