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
in 54 59 bytes:
function is_prime($n){for($i=$n;--$i&&$n%$i;);return$i==1;}
loops $i down from $n-1 until it finds a divisor of $n; $n is prime if that divisor is 1.
add 10 bytes for much better performance:
function is_prime($n){for($i=$n**.5|1;$i&&$n%$i--;);return!$i&&$n>1;}
loops $i from (approx.) sqrt($n) to 1 looking for a divisor with a post-decrement on $i.
If the divisor is 1, $i will be 0 at the end, and !$i gives true.
This solition uses a trick: For $n=2 or 3, $i will be initialized to 1 → loop exits in first iteration. For larger even square roots ($n**.5|0), |1 serves as +1. For odd square roots, +1 is not needed because: if $n is divisible by root+1, it is also divisible by 2. Unfortunately, this can cost a lot of iterations; so you better
add another 7 bytes for even better performance:
function is_prime($n){for($i=~-$n**.5|0;$i&&$n%$i--;);return!$i&$n>2|$n==2;}
$n=2 needs a special case here: inital $i=2 divides $n=2 → final $i=1 → returns false.
Adding 1 to $n instead of the square root is enough to avoid failures; but:
I did not count the iterations but only tested time consumption; and that only in TiO instead of a controlled environment. The difference between the last two versions was smaller than the deviation between several runs. Significant test results may be added later.