BAEL-1296 Prime numbers till n. (#2956)

* BAEL-1296 Prime numbers till n.

* BAEL-1296 Renamed packge
This commit is contained in:
Muhammed Almas 2017-11-10 01:24:36 +05:30 committed by Grzegorz Piwowarek
parent 6a8ecab163
commit a38e6e295e
2 changed files with 87 additions and 0 deletions

View File

@ -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<Integer> 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<Integer> primes = new LinkedList<>();
for (int i = 2; i <= n; i++) {
if (prime[i])
primes.add(i);
}
return primes;
}
public static List<Integer> primeNumbersBruteForce(int max) {
final List<Integer> primeNumbers = new LinkedList<Integer>();
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<Integer> 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);
}
}

View File

@ -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<Integer> primeNumbers = primeNumbersBruteForce(20);
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
}
@Test
public void whenOptimized_returnsSuccessfully() {
final List<Integer> primeNumbers = primeNumbersTill(20);
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
}
@Test
public void whenSieveOfEratosthenes_returnsSuccessfully() {
final List<Integer> primeNumbers = sieveOfEratosthenes(20);
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
}
}