Print every prime number up to n, and how many there are.
What to build
A program with one loop inside another, in which the inner loop can stop early.
Requirements
- Read a whole number n.
- Print all the primes from 2 to n on one line, separated by single spaces.
- Print
count: Kon the next line.
Input
One whole number n.
Output
Two lines.
Constraints
n is from 2 to 5000.
Example
Input:
10
Output:
2 3 5 7
count: 4
Why it works
If a number has a divisor larger than its square root, it must also have one smaller, so testing up to the square root is enough. break ends the inner loop at the first divisor, because one divisor is already proof.
Examples
Example 1 · Input
10
Expected output
2 3 5 7 count: 4
Example 2 · Input
2
Expected output
2 count: 1
Hints
Hint 1
A prime has no divisor other than 1 and itself.
Hint 2
Use one loop for each candidate, and an inner loop to look for a divisor.
Hint 3
You only need to try divisors d while d * d <= candidate, and you can break at the first one you find.
Solution
Show one correct solution (try it yourself first)
const n = Number(prompt());
let line = "";
let count = 0;
for (let candidate = 2; candidate <= n; candidate++) {
let prime = true;
for (let d = 2; d * d <= candidate; d++) {
if (candidate % d === 0) {
prime = false;
break;
}
}
if (prime) {
line += (count === 0 ? "" : " ") + candidate;
count++;
}
}
console.log(line);
console.log(`count: ${count}`);