4
4
5
5
/**
6
6
* Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers
7
- * up to any given limit. It does so by iteratively marking as composite (i.e.,
8
- * not prime) the multiples of each prime, starting with the first prime number,
9
- * 2. The multiples of a given prime are generated as a sequence of numbers
10
- * starting from that prime, with constant difference between them that is equal
11
- * to that prime. This is the sieve's key distinction from using trial division
12
- * to sequentially test each candidate number for divisibility by each prime.
13
- * Once all the multiples of each discovered prime have been marked as
14
- * composites, the remaining unmarked numbers are primes.
15
- * <p>
16
- * Poetry about Sieve of Eratosthenes:
17
- * <p>
18
- * <i>Sift the Two's and Sift the Three's:</i></p>
19
- * <p>
20
- * <i>The Sieve of Eratosthenes.</i></p>
21
- * <p>
22
- * <i>When the multiples sublime,</i></p>
23
- * <p>
24
- * <i>The numbers that remain are Prime.</i></p>
7
+ * up to any given limit.
25
8
*
26
9
* @see <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Wiki</a>
27
10
*/
28
11
public class SieveOfEratosthenes {
29
12
30
13
/**
31
- * @param n The number till which we have to check for prime Prints all the
32
- * prime numbers till n. Should be more than 1.
33
- * @return array of all prime numbers between 0 to n
14
+ * Finds all prime numbers till n.
15
+ *
16
+ * @param n The number till which we have to check for primes. Should be more than 1.
17
+ * @return Array of all prime numbers between 0 to n.
34
18
*/
35
19
public static int [] findPrimesTill (int n ) {
36
- // Create array where index is number and value is flag - is that number a prime or not.
37
- // size of array is n + 1 cause in Java array indexes starts with 0
38
20
Type [] numbers = new Type [n + 1 ];
39
-
40
- // Start with assumption that all numbers except 0 and 1 are primes.
41
21
Arrays .fill (numbers , Type .PRIME );
42
22
numbers [0 ] = numbers [1 ] = Type .NOT_PRIME ;
43
23
44
24
double cap = Math .sqrt (n );
45
- // Main algorithm: mark all numbers which are multiples of some other values as not prime
46
25
for (int i = 2 ; i <= cap ; i ++) {
47
26
if (numbers [i ] == Type .PRIME ) {
48
27
for (int j = 2 ; i * j <= n ; j ++) {
@@ -51,7 +30,6 @@ public static int[] findPrimesTill(int n) {
51
30
}
52
31
}
53
32
54
- //Write all primes to result array
55
33
int primesCount = (int ) Arrays
56
34
.stream (numbers )
57
35
.filter (element -> element == Type .PRIME )
0 commit comments