Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 60 / 68

Checking Whether a Number Is Prime

In this lesson you will learn the algorithm for testing whether a number is prime and understand how to make it efficient. This is for anyone searching for "PHP prime number check".

To decide whether a number is prime (divisible only by 1 and itself), check whether it divides evenly by anything from 2 up to its square root. If nothing divides it, it is prime.

The sample code uses the condition $i * $i <= $n, which effectively loops only as far as the square root. Written this way, the algorithm avoids the cost of computing a square root at all - a small but neat refinement.

A common stumbling block for beginners is understanding why the square root is enough. Any pair of numbers that multiply to give $n always has one member at or below the square root and the other at or above it, so checking up to the square root covers every case.

This is an important mathematical property that also underpins cryptography, and good practice at designing an efficient test. There is a more advanced technique, the Sieve of Eratosthenes, for finding many primes efficiently at once.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)