CBH
CBH

Reputation: 95

Determining Prime Numbers Java

I am writing a program that takes as input an integer, and outputs a message whether the integer entered is prime or not. The algorithm I am using is as follows... Require: n>0, Require: isPrime <- true, for i=2 to sqrt(n) do, if n%i=0 then isPrime <- false end if and end for Then Print whether the number is Prime or not. Here is my code so far, the code is not working and I am not able to find the problem.

     public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    int n;
    System.out.println("Input a positive integer");
    n = kb.nextInt();

        while (n>0){
            boolean isPrime = true;
            for (int i =2; i <= n/2;i++){
                if(n % i == 0){
                    isPrime = false;
                    break;
                }
            }
            if (isPrime = true){
                System.out.println("The integer, " + n + ", is a prime");
                break;
            }
            else{
                System.out.println("The integer, " + n + ", is not a prime");
                break;
            }
        }
    }
}

I would be grateful if someone could help, Thanks!

Upvotes: 2

Views: 28955

Answers (2)

Celeritas
Celeritas

Reputation: 15033

In the text you say the algorithm you intend to implement checks integers up to the square root of n but your code is going all the way up to n/2 (see the for loop).

The reason your current code isn't working is because if (isPrime = true) is an assignment operation and should be comparison if (isPrime == true) note the two equal signs.

Upvotes: 1

rgettman
rgettman

Reputation: 178243

Your problem lies with this line:

if (isPrime = true){

You made an assignment, instead of comparing to true, so the statement is always true.

Use == to compare boolean values, or better yet, since isPrime is already a boolean:

if (isPrime){

Upvotes: 8

Related Questions