The Challenge
Implement the Sundaram sieve for finding prime numbers below n
. Take an input integer, n
, and output the prime numbers below n
. You can assume that n
will always be less than or equal to one million.
Sieve
Start with a list of the integers from
1
ton
.Remove all numbers that are in the form
i + j + 2ij
where:i
andj
are less thann
.j
is always greater than or equal toi
, which is greater than or equal to1
.i + j + 2ij
is less than or equal ton
Multiply the remaining numbers by
2
, and add1
.
This will yield all the prime numbers (except 2
, which should be included in your output) less than 2n + 2
.
Here is an animation of the sieve being used to find primes below 202
.
Output
Your output should be every prime integer ≤ n
(in ascending order) followed by a newline:
2
3
5
Where n
is 5
.
Examples
> 10
2
3
5
7
> 30
2
3
5
7
11
13
17
19
23
29
Inputs are denoted by >
.
n=30
is missing 29 in the output. \$\endgroup\$(i,j)
withi<=j
, but the result doesn't change if we ignore this requirement. Can we do so to save bytes? \$\endgroup\$i <= j
. It's just part of how the sieve works. So yes, you can leave out thei <= j
in your code. @xnor \$\endgroup\$2n+1
) which are not of the form2(i + j + 2ij)+1
- can we test this property directly on the potential primes or does our code have to do the times 2 plus 1 at some point? \$\endgroup\$n
is in the whole thing. In the method description, it says that it will generate all primes up to2 * n + 2
. But in the input/output description, it says that the input isn
, and the output all primes up ton
. So are we supposed to apply the method to generate all primes up to2 * n + 2
, and then drop the ones larger thann
for the output? Or should we calculate then
in the method description from the inputn
? \$\endgroup\$