Use a small function to keep a bigger loop easy to read.
What to build
A program that lists the prime numbers up to n.
Requirements
- Write a function
isPrimethat tells whether a number is prime. - Read n and print all primes from 2 to n separated by spaces, or
noneif there are no primes.
Input
One integer n.
Output
One line.
Constraints
0 ≤ n ≤ 1000.
Example
Input:
20
Output:
2 3 5 7 11 13 17 19
Why it works
The helper function answers one clear question, so the main loop reads like the problem text.
Examples
Example 1 · Input
20
Expected output
2 3 5 7 11 13 17 19
Example 2 · Input
1
Expected output
none
Hints
Hint 1
Write function isPrime(int $n): bool that tries the divisors from 2 while d * d <= n.
Hint 2
Collect the primes in an array and join it with implode; print none when the array is empty.
Solution
Show one correct solution (try it yourself first)
<?php
function isPrime(int $n): bool
{
if ($n < 2) {
return false;
}
for ($d = 2; $d * $d <= $n; $d++) {
if ($n % $d === 0) {
return false;
}
}
return true;
}
$n = (int) trim(fgets(STDIN));
$primes = [];
for ($i = 2; $i <= $n; $i++) {
if (isPrime($i)) {
$primes[] = $i;
}
}
echo $primes ? implode(" ", $primes) : "none", "\n";