简体   繁体   中英

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.

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(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!" 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. This would be after the for loop is done checking all the numbers below currentNum .

General hint: Speed up your code by looping to the square root of currentNum , not currentNum itself. It's equivalent to what you have now, but faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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