How does this prime number test in Java work?

Adam Staples picture Adam Staples · Oct 22, 2013 · Viewed 80.1k times · Source

The code snippet below checks whether a given number is a prime number. Can someone explain to me why this works? This code was on a study guide given to us for a Java exam.

public static void main(String[] args)
{    
    int j = 2;
    int result = 0;
    int number = 0;
    Scanner reader = new Scanner(System.in);
    System.out.println("Please enter a number: ");
    number = reader.nextInt();
    while (j <= number / 2)
    {
        if (number % j == 0)
        {
           result = 1;
        }
        j++;
    }
    if (result == 1)
    {
        System.out.println("Number: " + number + " is Not Prime.");
    }
    else
    {
        System.out.println("Number: " + number + " is Prime. ");
    }
}

Answer

Richard Tingle picture Richard Tingle · Oct 22, 2013

Overall theory

The condition if (number % j == 0) asks if number is exactly divisible by j

The definition of a prime is

a number divisible by only itself and 1

so if you test all numbers between 2 and number, and none of them are exactly divisible then it is a prime, otherwise it is not.

Of course you don't actually have to go all way to the number, because number cannot be exactly divisible by anything above half number.

Specific sections

While loop

This section runs through values of increasing j, if we pretend that number = 12 then it will run through j = 2,3,4,5,6

  int j = 2;
  .....
  while (j <= number / 2)
  {
      ........
      j++;
  }

If statement

This section sets result to 1, if at any point number is exactly divisible by j. result is never reset to 0 once it has been set to 1.

  ......
  if (number % j == 0)
  {
     result = 1;
  }
  .....

Further improvements

Of course you can improve that even more because you actually need go no higher than sqrt(number) but this snippet has decided not to do that; the reason you need go no higher is because if (for example) 40 is exactly divisible by 4 it is 4*10, you don't need to test for both 4 and 10. And of those pairs one will always be below sqrt(number).

It's also worth noting that they appear to have intended to use result as a boolean, but actually used integers 0 and 1 to represent true and false instead. This is not good practice.