Skip to content

Commit f35e9a7

Browse files
authored
Update SieveOfEratosthenes.java (TheAlgorithms#4149)
1 parent 8798e04 commit f35e9a7

File tree

1 file changed

+5
-27
lines changed

1 file changed

+5
-27
lines changed

src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java

Lines changed: 5 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -4,45 +4,24 @@
44

55
/**
66
* 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.
258
*
269
* @see <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Wiki</a>
2710
*/
2811
public class SieveOfEratosthenes {
2912

3013
/**
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.
3418
*/
3519
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
3820
Type[] numbers = new Type[n + 1];
39-
40-
// Start with assumption that all numbers except 0 and 1 are primes.
4121
Arrays.fill(numbers, Type.PRIME);
4222
numbers[0] = numbers[1] = Type.NOT_PRIME;
4323

4424
double cap = Math.sqrt(n);
45-
// Main algorithm: mark all numbers which are multiples of some other values as not prime
4625
for (int i = 2; i <= cap; i++) {
4726
if (numbers[i] == Type.PRIME) {
4827
for (int j = 2; i * j <= n; j++) {
@@ -51,7 +30,6 @@ public static int[] findPrimesTill(int n) {
5130
}
5231
}
5332

54-
//Write all primes to result array
5533
int primesCount = (int) Arrays
5634
.stream(numbers)
5735
.filter(element -> element == Type.PRIME)

0 commit comments

Comments
 (0)