Skip to content

Commit c6880c1

Browse files
authored
feat: add Sieve of Eratosthenes algorithm (#7071)
* feat: add Sieve of Eratosthenes algorithm - Implement Sieve of Eratosthenes for finding prime numbers up to n - Add comprehensive unit tests with edge cases - Include JavaDoc documentation - Time complexity: O(n log log n) - Space complexity: O(n) Resolves #6939 * fix: remove trailing spaces * fix: apply clang-format
1 parent 9381161 commit c6880c1

File tree

2 files changed

+96
-62
lines changed

2 files changed

+96
-62
lines changed
Lines changed: 57 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,82 @@
11
package com.thealgorithms.maths;
22

3-
import java.util.Arrays;
3+
import java.util.ArrayList;
4+
import java.util.List;
45

56
/**
6-
* @brief utility class implementing <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes</a>
7+
* Sieve of Eratosthenes Algorithm
8+
* An efficient algorithm to find all prime numbers up to a given limit.
9+
*
10+
* Algorithm:
11+
* 1. Create a boolean array of size n+1, initially all true
12+
* 2. Mark 0 and 1 as not prime
13+
* 3. For each number i from 2 to sqrt(n):
14+
* - If i is still marked as prime
15+
* - Mark all multiples of i (starting from i²) as not prime
16+
* 4. Collect all numbers still marked as prime
17+
*
18+
* Time Complexity: O(n log log n)
19+
* Space Complexity: O(n)
20+
*
21+
* @author Navadeep0007
22+
* @see <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes</a>
723
*/
824
public final class SieveOfEratosthenes {
25+
926
private SieveOfEratosthenes() {
27+
// Utility class, prevent instantiation
1028
}
1129

12-
private static void checkInput(int n) {
13-
if (n <= 0) {
14-
throw new IllegalArgumentException("n must be positive.");
30+
/**
31+
* Finds all prime numbers up to n using the Sieve of Eratosthenes algorithm
32+
*
33+
* @param n the upper limit (inclusive)
34+
* @return a list of all prime numbers from 2 to n
35+
* @throws IllegalArgumentException if n is negative
36+
*/
37+
public static List<Integer> findPrimes(int n) {
38+
if (n < 0) {
39+
throw new IllegalArgumentException("Input must be non-negative");
1540
}
16-
}
1741

18-
private static Type[] sievePrimesTill(int n) {
19-
checkInput(n);
20-
Type[] isPrimeArray = new Type[n + 1];
21-
Arrays.fill(isPrimeArray, Type.PRIME);
22-
isPrimeArray[0] = Type.NOT_PRIME;
23-
isPrimeArray[1] = Type.NOT_PRIME;
42+
if (n < 2) {
43+
return new ArrayList<>();
44+
}
45+
46+
// Create boolean array, initially all true
47+
boolean[] isPrime = new boolean[n + 1];
48+
for (int i = 2; i <= n; i++) {
49+
isPrime[i] = true;
50+
}
2451

25-
double cap = Math.sqrt(n);
26-
for (int i = 2; i <= cap; i++) {
27-
if (isPrimeArray[i] == Type.PRIME) {
28-
for (int j = 2; i * j <= n; j++) {
29-
isPrimeArray[i * j] = Type.NOT_PRIME;
52+
// Sieve process
53+
for (int i = 2; i * i <= n; i++) {
54+
if (isPrime[i]) {
55+
// Mark all multiples of i as not prime
56+
for (int j = i * i; j <= n; j += i) {
57+
isPrime[j] = false;
3058
}
3159
}
3260
}
33-
return isPrimeArray;
34-
}
35-
36-
private static int countPrimes(Type[] isPrimeArray) {
37-
return (int) Arrays.stream(isPrimeArray).filter(element -> element == Type.PRIME).count();
38-
}
3961

40-
private static int[] extractPrimes(Type[] isPrimeArray) {
41-
int numberOfPrimes = countPrimes(isPrimeArray);
42-
int[] primes = new int[numberOfPrimes];
43-
int primeIndex = 0;
44-
for (int curNumber = 0; curNumber < isPrimeArray.length; ++curNumber) {
45-
if (isPrimeArray[curNumber] == Type.PRIME) {
46-
primes[primeIndex++] = curNumber;
62+
// Collect all prime numbers
63+
List<Integer> primes = new ArrayList<>();
64+
for (int i = 2; i <= n; i++) {
65+
if (isPrime[i]) {
66+
primes.add(i);
4767
}
4868
}
69+
4970
return primes;
5071
}
5172

5273
/**
53-
* @brief finds all of the prime numbers up to the given upper (inclusive) limit
54-
* @param n upper (inclusive) limit
55-
* @exception IllegalArgumentException n is non-positive
56-
* @return the array of all primes up to the given number (inclusive)
74+
* Counts the number of prime numbers up to n
75+
*
76+
* @param n the upper limit (inclusive)
77+
* @return count of prime numbers from 2 to n
5778
*/
58-
public static int[] findPrimesTill(int n) {
59-
return extractPrimes(sievePrimesTill(n));
60-
}
61-
62-
private enum Type {
63-
PRIME,
64-
NOT_PRIME,
79+
public static int countPrimes(int n) {
80+
return findPrimes(n).size();
6581
}
6682
}
Lines changed: 39 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,64 @@
11
package com.thealgorithms.maths;
22

3-
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
44
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
import static org.junit.jupiter.api.Assertions.assertTrue;
56

7+
import java.util.Arrays;
8+
import java.util.List;
69
import org.junit.jupiter.api.Test;
710

11+
/**
12+
* Test cases for Sieve of Eratosthenes algorithm
13+
*
14+
* @author Navadeep0007
15+
*/
816
class SieveOfEratosthenesTest {
17+
18+
@Test
19+
void testPrimesUpTo10() {
20+
List<Integer> expected = Arrays.asList(2, 3, 5, 7);
21+
assertEquals(expected, SieveOfEratosthenes.findPrimes(10));
22+
}
23+
24+
@Test
25+
void testPrimesUpTo30() {
26+
List<Integer> expected = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
27+
assertEquals(expected, SieveOfEratosthenes.findPrimes(30));
28+
}
29+
930
@Test
10-
public void testfFindPrimesTill1() {
11-
assertArrayEquals(new int[] {}, SieveOfEratosthenes.findPrimesTill(1));
31+
void testPrimesUpTo2() {
32+
List<Integer> expected = Arrays.asList(2);
33+
assertEquals(expected, SieveOfEratosthenes.findPrimes(2));
1234
}
1335

1436
@Test
15-
public void testfFindPrimesTill2() {
16-
assertArrayEquals(new int[] {2}, SieveOfEratosthenes.findPrimesTill(2));
37+
void testPrimesUpTo1() {
38+
assertTrue(SieveOfEratosthenes.findPrimes(1).isEmpty());
1739
}
1840

1941
@Test
20-
public void testfFindPrimesTill4() {
21-
var primesTill4 = new int[] {2, 3};
22-
assertArrayEquals(primesTill4, SieveOfEratosthenes.findPrimesTill(3));
23-
assertArrayEquals(primesTill4, SieveOfEratosthenes.findPrimesTill(4));
42+
void testPrimesUpTo0() {
43+
assertTrue(SieveOfEratosthenes.findPrimes(0).isEmpty());
2444
}
2545

2646
@Test
27-
public void testfFindPrimesTill40() {
28-
var primesTill40 = new int[] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};
29-
assertArrayEquals(primesTill40, SieveOfEratosthenes.findPrimesTill(37));
30-
assertArrayEquals(primesTill40, SieveOfEratosthenes.findPrimesTill(38));
31-
assertArrayEquals(primesTill40, SieveOfEratosthenes.findPrimesTill(39));
32-
assertArrayEquals(primesTill40, SieveOfEratosthenes.findPrimesTill(40));
47+
void testNegativeInput() {
48+
assertThrows(IllegalArgumentException.class, () -> { SieveOfEratosthenes.findPrimes(-1); });
3349
}
3450

3551
@Test
36-
public void testfFindPrimesTill240() {
37-
var primesTill240 = new int[] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239};
38-
assertArrayEquals(primesTill240, SieveOfEratosthenes.findPrimesTill(239));
39-
assertArrayEquals(primesTill240, SieveOfEratosthenes.findPrimesTill(240));
52+
void testCountPrimes() {
53+
assertEquals(4, SieveOfEratosthenes.countPrimes(10));
54+
assertEquals(25, SieveOfEratosthenes.countPrimes(100));
4055
}
4156

4257
@Test
43-
public void testFindPrimesTillThrowsExceptionForNonPositiveInput() {
44-
assertThrows(IllegalArgumentException.class, () -> SieveOfEratosthenes.findPrimesTill(0));
58+
void testLargeNumber() {
59+
List<Integer> primes = SieveOfEratosthenes.findPrimes(1000);
60+
assertEquals(168, primes.size()); // There are 168 primes up to 1000
61+
assertEquals(2, primes.get(0)); // First prime
62+
assertEquals(997, primes.get(primes.size() - 1)); // Last prime up to 1000
4563
}
4664
}

0 commit comments

Comments
 (0)