- Factors
- 2, 2, 2, 7
Find Prime Factors in PHP
What you’ll learn
- What prime factors are (primes you multiply to rebuild a number).
- A trial division program that prints factors in order, using the same idea as the reference code but with clearer names.
- A faster version that peels off 2, then tests odd divisors only up to roughly the square root.
- A live preview, input guards (so
0does not loop forever), and usual edge cases.
Overview
Take 56. You can split it as 56 = 2 × 28 = 2 × 2 × 14 = 2 × 2 × 2 × 7. The primes that show up are 2 (three times) and 7 (once). This page prints that list: 2 2 2 7. The algorithm tries small divisors in order, strips each as many times as it can, and shrinks what is left until nothing is left to strip.
Two programs
Example 1 is the short double loop (easy to explain). Example 2 is the usual interview upgrade.
Live preview
Type 56, 17 (prime), or 360 before compiling.
Safe inputs
We require n >= 2 so 0 cannot get stuck dividing forever.
Prerequisites
for and while loops, remainder %, and integer division /.
- Rough idea of prime: a whole number > 1 whose only positive divisors are 1 and itself (2, 3, 5, 7, 11…).
- PHP output with
echo, plus casting and integer arithmetic.
What are prime factors?
Prime factors are prime numbers that multiply together to give your starting number. The order we print them is smallest first; repeated primes mean “that prime appears more than once.”
This is not the same lesson as “odd numbers”—the old reference page had a copy-paste heading mistake there. Here we stay on factorization the whole time.
Why trying 2, 3, 4, … still works
When i is composite (say 6), its prime pieces (2 and 3) were already removed from the running value x. So 6 cannot divide x anymore unless you missed an earlier factor—you did not. That is why a plain “does it divide?” test is enough without calling a separate isPrime function in this pattern.
If you multiply every printed factor together, you get the original n (for n >= 2). For a prime like 17, the only factor listed is 17.
Quick examples
- Factors
- 17 only
- Starts with
- 2, 2, 2, 3, 3, 5 …
Live preview
Uses the same fast pattern as Example 2 (twos, then odd trial divisors). Capped so inputs stay responsive.
Algorithm (trial division)
Goal: print every prime factor of n (with repetition), in non-decreasing order, for integers n >= 2.
Validate n
If n < 2, stop or print a message (no prime factorization in this basic form).
Try divisors in order
Let i run from 2 upward. While the current remainder is divisible by i, print i and divide the remainder by i.
Stop when remainder is 1
In the simple version, the for loop can stop when the remainder reaches 1; the code on this page keeps the reference style i <= x for clarity.
📜 Pseudocode
procedure displayPrimeFactors(n):
if n < 2:
report invalid / stop
x ← n
for i from 2 while i <= x:
while x mod i = 0:
output i
x ← x / iStraightforward trial division
Same structure as the reference program: divides_evenly is just a readable name for “remainder is zero.” We guard n < 2 so 0 never enters an infinite while (x % 2 == 0) loop.
<?php
function dividesEvenly(int $a, int $b): bool
{
return $a % $b === 0;
}
function displayPrimeFactors(int $n): void
{
if ($n < 2) {
echo "Enter an integer n >= 2 (got $n).\n";
return;
}
echo "Prime factors of $n are: ";
$x = $n;
for ($i = 2; $i <= $x; $i++) {
while (dividesEvenly($x, $i)) {
echo $i . " ";
$x = (int)($x / $i);
}
}
echo "\n";
}
$number = 56;
displayPrimeFactors($number);
?>Explanation
Start with x = 56. At i = 2, peel three twos (56 → 28 → 14 → 7). Later i = 7 peels the seven. The remainder becomes 1 and the loop finishes.
Peel 2, then odd divisors up to √x
After removing all factors of 2, test only odd i. Stop when i × i exceeds the current remainder. If anything is left above 1, it is prime. Same printed line for 56 as Example 1.
<?php
function displayPrimeFactorsFast(int $n): void
{
if ($n < 2) {
echo "Enter an integer n >= 2 (got $n).\n";
return;
}
echo "Prime factors of $n are: ";
$x = $n;
while ($x % 2 === 0) {
echo "2 ";
$x = (int)($x / 2);
}
for ($i = 3; $i * $i <= $x; $i += 2) {
while ($x % $i === 0) {
echo $i . " ";
$x = (int)($x / $i);
}
}
if ($x > 1) {
echo $x . " ";
}
echo "\n";
}
$number = 56;
displayPrimeFactorsFast($number);
?>Explanation
The loop condition $i * $i <= $x gives the square-root stopping rule. The final if ($x > 1) catches one large prime left over (for example after trial division on a semiprime).
Notes
Wheel / sieve. For many queries, sieves or precomputed primes beat naive trial division; for one interview number, Example 2 is usually enough.
Types. PHP integers are platform dependent (typically 64-bit). For very large values, consider GMP/BCMath if exact large-integer factorization is required.
Related: prime check, composite numbers, and GCD build on the same divisor ideas.
❓ FAQ
🔄 Input / output examples
Change $number in the script or read with $number = (int)trim(fgets(STDIN)); in PHP CLI.
n | Printed factors (conceptually) |
|---|---|
| 56 | 2 2 2 7 |
| 17 | 17 |
| 12 | 2 2 3 |
| 1 | Error line from guard (no factorization) |
Edge cases
The reference code did not guard small values; these fixes keep homework answers safe.
n = 0Infinite loop risk
Naive while (x % 2 == 0) on x = 0 never progresses. Always reject n < 2 first.
n = 1Empty product
Standard factorization starts at n >= 2. Say so in the message you print.
Repeated primes
36 prints 2 2 3 3—duplicates are expected.
⏱️ Time and space complexity
| Version | Time (single n) | Extra space |
|---|---|---|
Example 1 (try every i up to current x) | worst case about O(n) when n is prime | O(1) |
| Example 2 (√ bound) | O(√n) trial divisions typical story | O(1) |
Summary
- Idea: strip smallest divisors first; what you print are prime factors in order.
- Code: guard
n < 2;for+ innerwhile(Example 1) or 2 + odds + leftover (Example 2). - Fixes vs naive reference: correct topic heading, honest helper name, no infinite loop on
0.
The fundamental theorem of arithmetic says: every integer greater than 1 can be written as a product of primes in exactly one way if you ignore order. That is why “listing prime factors” feels so tidy—you are reading off that unique recipe.
8 people found this page helpful
