Criticize the code

<?php function isPrime($num) { if ($num < 2) { echo "$num is not prime"; exit(); } for ($i = 2; $i < $num; $i++) { if ($num % $i == 0) { echo "$num is not prime"; exit(); } } echo "$num is prime"; } isPrime(13); ?> 

Why do you need the square root in the expression for ($i = 2; $i < $num; $i++) if everything works so well ... But how can you convert this code so that you can search for primes in the range from 2 to 13?

  • Why do we need the square root in the expression, so if everything works , it will significantly reduce the number of checks that need to be done to determine the simplicity. The greater the number you need to check - the greater the difference will be - Grundy

1 answer 1

A good function, just need to comb a little so that you can use and understand what the result is.

 function isPrime($num) { $num = (int)$num; //вдруг передали ерунду? if ($num < 2) { return false; } for ($i = 2; $i < $num; $i++) { if ($num % $i == 0) { return $i; } } return true; } 

I ran it on the first 20 primes of the form x ^ 4 + 1, a very decent result. The number 655360001 was checked for simplicity for 59 seconds.

Although, of course, this algorithm is not suitable for mining Bitcoins. You can forever mine and don't blame anything :)

Example:

 $i = 0; while ($i<100) { $isPrime = isPrime($i); if ( $isPrime === true) { echo "$i is prime" . PHP_EOL; } else if($isPrime === false) { echo "$i is NOT prime, because negative numbers, zero and 1 are not primes" . PHP_EOL; } else { echo "$i is NOT prime, the divider is {$isPrime}" . PHP_EOL; } $i++; } 
  • PHP_EOL can be omitted from this code as it simply checks the number passed to the function for simplicity. And how to modify to check and derive prime numbers from 2 to 13 for example - Beginner
  • Well, he ehoets everything in a row - you need to complete the line, although of course this is not necessary, just ugly. - Denis Matafonov
  • threw an example of use - Denis Matafonov