# Need help explaining how this prime number program works

2280 views
2

I have this code here that asks a user to enter a number then calls the `isPrime` method to calculate if the number is prime or not. It then prints out to the screen the result. I did a lot of trial and error to get this code to work, but I don't really understand all the way why this program works. For instance if I enter 9, the code would give me back a remainder, which should return true, which should make 9 a prime number, but it's not and the program works, saying that 9 is not a prime number. Just wondering why it works.

``````package homework_chap5;
``````

import java.util.Scanner;

public class Homework_Chap5 {

``````        //Pg 313 #7

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter number: ");
int num = s.nextInt();

if(isPrime(num)) {

System.out.println("Number is prime");

} else {

System.out.println("Number is not prime");
}

}

public static boolean isPrime(int num)
{

for(int i = 2; i <= num/2; i++)
{
if (num%i==0)
{
return false;
}

}
return true;

}
``````

}

4

For instance if I enter 9, the code would give me back a remainder, which should return true

No, for `num==9` and `i==2`, `num%i==0` will be `false`, but the loop will proceed to check for `i==3` whether `num%i==0`. This time the condition will be true and the `isPrime` method with return `false`.

Only after the loop ends, at which point we know that `num` is not divisible by any of the values of `i` tested, the method will conclude that `num` is a prime number and return `true`.

posted this

JD