Check if an int is prime Java

会有一股神秘感。 提交于 2021-02-05 07:00:36

问题


sorry for the "fix my code" post

EDIT: related more to syntax of a for loop than prime numbers, also solved now.

My task is to take an int from the console and print out (on separate lines) all the prime numbers from 1 to n inclusive. My method starts at n, checks if its prime, then increments n down by one and loops until n=2. To check if a number is prime I run a loop, checking is the remainder of diving the number by x is equal to zero, with x starting at 2 and stopping at root(n). Now this all works in theory, and reading my code I don't see where it goes wrong.

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--;
        }
    }
  }
}

For example an input of 10 will return 10 (along with 9,8,7,6,5,3), even though isPrime() checks if 10 % 2 == 0, then sets result to false. What am I missing here??

Again I apologise for the annoying (slightly duplicate) question.


回答1:


The condition in the for loop is the condition to continue the loop, not the condition to stop it. You need to replace >= with <=:

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



回答2:


You are incrementing x twice, and the loop's condition should be x<=sqrt(n) :

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

The correct logic should be:

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



回答3:


In the loop x must be less than or equal to So change the expression for (int x = 2; x>=sqrt(n); x++) to for (int x = 2; x<=sqrt(n); x++)




回答4:


Try it this way, it's much clearer and concise.

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);


    }


来源:https://stackoverflow.com/questions/45530924/check-if-an-int-is-prime-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!