diff --git a/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java b/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java new file mode 100644 index 0000000000..48d51a8848 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java @@ -0,0 +1,59 @@ +package com.baeldung.algorithms.prime; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class PrimeGenerator { + public static List sieveOfEratosthenes(int n) { + final boolean prime[] = new boolean[n + 1]; + Arrays.fill(prime, true); + + for (int p = 2; p * p <= n; p++) { + if (prime[p]) { + for (int i = p * 2; i <= n; i += p) + prime[i] = false; + } + } + + final List primes = new LinkedList<>(); + for (int i = 2; i <= n; i++) { + if (prime[i]) + primes.add(i); + } + return primes; + } + + public static List primeNumbersBruteForce(int max) { + final List primeNumbers = new LinkedList(); + for (int i = 2; i <= max; i++) { + if (isPrimeBruteForce(i)) { + primeNumbers.add(i); + } + } + return primeNumbers; + } + + private static boolean isPrimeBruteForce(int x) { + for (int i = 2; i < x; i++) { + if (x % i == 0) { + return false; + } + } + return true; + } + + public static List primeNumbersTill(int max) { + return IntStream.rangeClosed(2, max) + .filter(x -> isPrime(x)) + .boxed() + .collect(Collectors.toList()); + } + + private static boolean isPrime(int x) { + return IntStream.rangeClosed(2, (int) (Math.sqrt(x))) + .allMatch(n -> x % n != 0); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java b/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java new file mode 100644 index 0000000000..4995e938b7 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java @@ -0,0 +1,28 @@ +package com.baeldung.algorithms.prime; + +import static com.baeldung.algorithms.prime.PrimeGenerator.*; + +import java.util.Arrays; +import java.util.List; +import org.junit.Test; +import static org.junit.Assert.*; + +public class PrimeGeneratorTest { + @Test + public void whenBruteForced_returnsSuccessfully() { + final List primeNumbers = primeNumbersBruteForce(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenOptimized_returnsSuccessfully() { + final List primeNumbers = primeNumbersTill(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenSieveOfEratosthenes_returnsSuccessfully() { + final List primeNumbers = sieveOfEratosthenes(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } +}