What is wrong with my isPrime method?

Viewed 73742

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?

13 Answers

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