How does the prime test in Java work?

The following code snippet checks whether a given number is prime Can someone explain to me why? This code is to give us a Java exam study guide

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. ");
    }
}

Solution

General theory

The conditional if (number% J = = 0) asks whether a number is completely divisible by J

A definition of quality is

So if you test all the numbers between 2 and the number, and none of them is completely separable, then it is a prime, otherwise it is not

Of course, you don't actually have to go to this number, because numbers can't be distinguished by anything more than half

Specific part

loop

This part runs by increasing the value of J. if we assume that the number = 12, then it will pass through J = 2,3,4,5,6

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

If statement

This section sets the result to 1. If at any point, the number can be divided by J Once set to 1, the result will never be reset to 0

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

Further improvement

Of course, you can improve or even more, because you actually need no more than sqrt, but this code segment has decided not to do so The reason you need will not be higher, because if (for example) 40 can be divided by 4, it is 4 * 10, and there is no need to test for 4 and 10 And those pairs will always be lower than sqrt

It's also worth noting that they seem to intend to use the result as a boolean, but actually use integers of 0 and 1 instead of true and false It's not a good habit

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>