简体   繁体   中英

What is wrong with my isPrime method?

This is my isPrime method:

private static boolean isPrime(int num) {
    if (num % 2 == 0) return false;
    for (int i = 3; i * i < num; i += 2)
        if (num % i == 0) return false;
    return true;
}

I put isPrime(9) and it returns true . What is wrong with the method?

Your condition should be i * i <= num

private static boolean isPrime(int num) 
{
        if (num == 2) 
            return true;
        if (num < 2 || num % 2 == 0) 
            return false;
        for (int i = 3; i * i <= num; i += 2)
            if (num % i == 0) 
                return false;
        return true;
}

You didn't take number 9 in your consideration so 9<9 will result false. But you need to check 9.

my sample:

public boolean isPrime(int x) {
    if (x==1) {
        return true;
    } else {
        for(int i=2;i<=Math.sqrt(x);i++) {
            if (x%i==0) return false;   
        }
    }
    return true;
}

Java 8: (Example with lambda expression and streams)

public static boolean isPrimeFunctionalStyle(int number) {
    return number > 1 && 
            IntStream.rangeClosed(2, (int) Math.sqrt(number))
                .noneMatch(i -> number % i == 0);
}

Here are some hints:

  1. The main bug is that you never check divisibility by sqrt(num) due to an off-by-one error in the loop.

  2. The other bug is that you don't consider 2 to be prime (which it is).

Change your code like this ( check condition) :

 private static boolean isPrime(int num) {
        if (num == 2) return true;
        if (num % 2 == 0)
            return false;
        for (int i = 3; i * i <= num; i += 2)
            if (num % i == 0) return false;
        return true;
  }  

(Late) Sidenode:

private static boolean isPrime(int num) {
    if (num % 2 == 0) return false;
    for (int i = 3; i * i < num; i += 2)
        if (num % i == 0) return false;
    return true;
}

This code is missing 2 ; 2 is a primenumber. Everything dividable by 2 isn't, except the 2 - so, use:

private static boolean isPrime(int num) {
    if (num == 2) return true;
    if (num % 2 == 0) return false;
    for (int i = 3; i * i < num; i += 2)
        if (num % i == 0) return false;
    return true;
}

i * i < num的循环条件应该是i * i <= num

循环永远不会执行,所以它直接返回真

The loop does not run. It gets terminated in the very first value of i because 3 x 3 = 9 it does not meet the condition i * i < n

 for (int i = 3; i * i < num; i += 2)
        if (num % i == 0) return false;

i * i is 9, and 9 in not less than 9, thus for loop is not run.

you can simply use if and else statement to check to see if the number is prime. There is a pattern, all the numbers are either multiples of either 2 or 3 once your number reach certain limits.

public static boolean isPrime2 (int n)
{
    if (n == 1) {
        return false;
    } else if (n == 2 || n==3) {
        return true;
    } else if (n>2) {
        if(n % 2 ==0 || n % 3 == 0) {
            return false;
        }
    }
    return true;
}
public static boolean isPrime (int number) {
    if(number < 2) {
        return false;
    }
    int check = (int) Math.sqrt(number);


    for(int i = 2; i <= check; i++) {
        if(number % i == 0) {
            return false;
        }
    }
    return true;
}
    package Prime;

import javax.swing.*;
import java.util.Scanner;

public class Prime {
    // main method
    public static void main(String[] args) {

        // declare lower bound and upper bound variables and get their values
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a Lower Bound number: ");
        int lowerBound = scanner.nextInt();

        System.out.print("Enter an Upper Bound number: ");
        int upperBound = scanner.nextInt();

        int counter;

        if ((lowerBound <= 0) || (upperBound <= 0)) {
            System.out.println("Bounds must be greater than 0, Invalid Bounds");
            } else if (upperBound < lowerBound) {
            System.out.println("Upper bound cannot be less than lower bound, Invalid Bounds\nProgram terminating.");
        } else {
            // loop from lower bound to upper bound
            System.out.println("The Prime numbers are: ");
            for (counter = lowerBound; counter <= upperBound;
                 counter++) {
                // if prime number, display in primeNumbersJTextArea
                if (isPrime(counter)) {
                    System.out.print(counter + ", ");
                }
            } // end for loop
        } // end else

    } // end method calculatePrimesJButtonActionPerformed


    // method to determine if a number is a Prime number?
    private static boolean isPrime(int number) {
        // number 1 is not a Prime number
        if (number == 1)
            return false;

        int limit = (int) Math.sqrt(number);

        for (int counter = 2; counter <= limit; counter++) {
            if (number % counter == 0) {
                return false;
            }
        }
        return true;
    }
}

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