Three methods for php to determine a number as a prime number, and three methods for php to determine a prime number
What is a prime number?
Prime number. A natural number greater than 1, except 1 and itself, cannot be divisible by other natural numbers called prime numbers; otherwise, it is called a union number. (Note: 1 is not a prime number .)
Method 1:
The basic method is the count method.
$ Num = 7; $ n = 0; // used to record the number of divisible items -- count for ($ I = 1; $ I <= $ num; ++ $ I) {if ($ num % $ I = 0) {$ n ++ ;}} if ($ n = 2) {echo "$ num is a prime number ";} else {echo "$ num is not a prime number ";}
Method 2:
When a number is equal to the product of two numbers, one of them must be less than half of the number. Use break. Once one of them can be wiped out, the cycle ends immediately. This reduces the number of cycles and speeds up the process.
$ Num = 5; $ flag = true; for ($ I = 2; $ I <= $ num/2; ++ $ I) {if ($ num % $ I = 0) {$ flag = false; break ;}} if ($ flag) {echo "$ num is a prime number ";} else {echo "$ num is not a prime number ";}
Method 3:
Same as above, when the product of two numbers multiplied is equal to one number, then one of them must be smaller than the square root of the number.
$ Num = 4; for ($ I = 2; $ I <$ num; ++ $ I) {if ($ num % $ I = 0) {echo "$ num is not a prime number"; break;} if ($ I >= sqrt ($ num) {echo "$ num is a prime number"; break ;}}