Hello i got little program here that checks if given number is prime number, but i dont understand some part in for loop and i need your help. here is the code:
public class PrimeNumber
{
public static void main(String args[])
{
int number;
boolean prime;
/*
*is a natural number greater than 1 that has no positive divisors other
*than 1 and itself.
* such as: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
* 61, 67, 71, 73, 79, 83, 89, 97, 101, and so on.
*/
number =23;
if(number<2)
prime=false;
else
prime=true;
for(int i=2; i <=number/2; i++)
{
if ((number%i) ==0)
{
prime =false;
break;
}
}
if(prime) System.out.println("It is prime number");
else System.out.println("it is not prime number");
}
}
I understand that first if function checks if given numbers is higher than 2 if it is not prime will be false, if it will prime will be true. Then in for loop i think int is 2 because 2 is the smallest possible prime number ? I understand <= this operator checks if i is less than or equal to number but i dont understand why we used number/2 ? and why we had to check if there is rest between these two numbers in last if function ?