I\'m trying to create a function which checks whether the number is prime or not. BUT I want this function to echo to the user \'prime\' or \'NOT prime\' - and that\'s where my
First, don't make a mistake here:
for ($i = 2; $i < $num; $i++)
and then:
if ($num % $i == 0) return false;
2 % 2 equals 0 and then 2 will result as NOT prime.
Next, you don't have to check even numbers, so after you check if $num == 2, better performance is:
for ($i = 3; $i < $num/2; $i += 2)
Notice $num/2 - you don't have to check beyond that point. And even better is:
for ($i = 3; $i*$i <= $num; $i += 2)
This is because when you check for division with 2 and 3 all other NON prime numbers are product of two (or more) prime numbers (e.g. 49 = 7*7 or 55 = 5*11). In the worst case scenario your $i pointer would reach a square root of $num (like in 49 = 7*7). That's why you check until $i*$i <= $num.