PHP Program to Check Prime Number with Output
for and checks divisibility with % operator to determine if it's prime.Examples
How to Think About It
Algorithm
Code
<?php function isPrime(int $num): bool { if ($num < 2) { return false; } $limit = (int) sqrt($num); for ($i = 2; $i <= $limit; $i++) { if ($num % $i === 0) { return false; } } return true; } $number = 17; if (isPrime($number)) { echo "$number is a prime number."; } else { echo "$number is not a prime number."; }
Dry Run
Let's trace the number 17 through the code to check if it is prime.
Check if number is less than 2
17 is not less than 2, so continue.
Calculate square root limit
Square root of 17 is about 4.12, so limit is 4.
Loop from 2 to 4 and check divisibility
Check 17 % 2, 17 % 3, 17 % 4; none are zero.
No divisors found
Return true, 17 is prime.
| i | num % i | Divisible? |
|---|---|---|
| 2 | 17 % 2 = 1 | No |
| 3 | 17 % 3 = 2 | No |
| 4 | 17 % 4 = 1 | No |
Why This Works
Step 1: Exclude numbers less than 2
Numbers less than 2 are not prime by definition, so we return false immediately.
Step 2: Check divisors up to square root
If a number has a divisor larger than its square root, it must also have a smaller one, so checking up to the square root is enough.
Step 3: Return result based on divisibility
If any divisor divides the number evenly, it is not prime; otherwise, it is prime.
Alternative Approaches
<?php function isPrime(int $num): bool { if ($num < 2) { return false; } for ($i = 2; $i < $num; $i++) { if ($num % $i === 0) { return false; } } return true; } $number = 17; if (isPrime($number)) { echo "$number is a prime number."; } else { echo "$number is not a prime number."; }
<?php function sievePrime(int $num): bool { if ($num < 2) return false; $sieve = array_fill(0, $num + 1, true); $sieve[0] = $sieve[1] = false; for ($i = 2; $i * $i <= $num; $i++) { if ($sieve[$i]) { for ($j = $i * $i; $j <= $num; $j += $i) { $sieve[$j] = false; } } } return $sieve[$num]; } $number = 17; if (sievePrime($number)) { echo "$number is a prime number."; } else { echo "$number is not a prime number."; }
Complexity: O(√n) time, O(1) space
Time Complexity
The loop runs up to the square root of the number, so time grows roughly with √n.
Space Complexity
Only a few variables are used, so space is constant O(1).
Which Approach is Fastest?
Checking divisibility up to the square root is faster than checking up to n-1. The sieve is faster for many numbers but uses more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Check up to √n | O(√n) | O(1) | Single number, simple code |
| Check up to n-1 | O(n) | O(1) | Simple but slow, not recommended |
| Sieve of Eratosthenes | O(n log log n) | O(n) | Many primes, batch processing |