Reputation: 119
Hello i'm new learner at java, the tutor on Udemy gave us this method but he didn't explain it, i found it hard to understand, and i tried to execute it, but still the same thing. PS : sorry for my English i'm Arabian. This is the method:
public static boolean isPrime(int n) {
if(n == 1) {
return false;
}
for(int i = 2; i <= n/2; i++) {
if(n % i == 0) {
return false;
}
}
return true;
}
Upvotes: 0
Views: 59
Reputation: 107
The method isPrime(int n)
takes an integer n
and checks whether it is prime or not.
First it checks whether n
is equal to 1. If it is the method returns false, because 1 is not prime.
Afterwards it loops through all the numbers between 2
and n/2
, and checks if n
is divisible by that number. If it is, the method returns false because then it is not prime.
The reason why it does not check every number from 2
til n
is because it would be redundant. The number n
can never be expressed as a product of a whole number and a number that is bigger than n/2
, except n
but then it would not be a prime number.
Upvotes: 0
Reputation: 261
The code loops through all numbers from 2
to n/2
and checks if n is divisible by that number. If it is divisible by any of these numbers the function returns false
as n has a divisor. If we have found no divisor from 2
to n/2
the number is prime. A better approach would be to loop to the square root of n.
Upvotes: 2