Sieve of Eratosthenes
Find all prime number in the range [1, max]
Goal
Find all prime number in the range [1, max]
Plan
Create a boolean array from [1,max], marking every prime number true
and non-prime false
.
Idea
- Initialize an array with size
max
- Fill each element of the array with
true
- Mark the element at [1] as
true
- For each element in the range [2, sqrt(max)]:
- If the element
j
istrue
(i.e. not touched by the algorithm yet):- Start from
i*i
:- Mark all multiplier of
j
(2j
,3j
,…) that is smaller thanmax
asfalse
- Mark all multiplier of
- Start from
- If the element
Why starts from
i*i
?
Because every number less than i2 is either a prime or has a divisor less than i.
Reason: if it has two divisors at least i, then its value is at least i2.
Java Code
1
2
3
4
5
6
7
8
9
10
boolean[] sieve = new boolean[1001];
Arrays.fill(sieve, true);
sieve[1] = false;
for (int i = 2; i <= Math.sqrt(1001); i++) {
if (sieve[i]) {
for (int j = i * i; j <= 1000; j += i) {
sieve[j] = false;
}
}
}
Example LeetCode problem
This post is licensed under CC BY 4.0 by the author.
Comments powered by Disqus.