diff --git a/numbers/Eratosthenes sieve/EratosthenesSieve.java b/numbers/Eratosthenes sieve/EratosthenesSieve.java new file mode 100644 index 00000000..1c0702c9 --- /dev/null +++ b/numbers/Eratosthenes sieve/EratosthenesSieve.java @@ -0,0 +1,34 @@ +import java.util.ArrayList; +import java.util.List; + +/** + * Parse first parameter as number n and return list of all prime numbers less or equal n. + * Time complexity is O(N * log(log N)), memory complexity is O(N) + */ +public class EratosthenesSieve { + public static void main(String[] args) { + int n = Integer.valueOf(args[0]); + List primeNumbers = sieve(n); + primeNumbers.forEach(EratosthenesSieve::print); + } + + private static List sieve(int n) { + List primeNumbers = new ArrayList<>(); + boolean[] nonPrimes = new boolean[n + 1]; + + for (int i = 2; i <= n; i++) { + if (!nonPrimes[i]) { + primeNumbers.add(i); + for (int j = i; j <= n / i; j++) { + nonPrimes[i * j] = true; + } + } + } + + return primeNumbers; + } + + private static void print(int x) { + System.out.printf("%d ", x); + } +} diff --git a/numbers/Eratosthenes sieve/EratosthenesSieve.scala b/numbers/Eratosthenes sieve/EratosthenesSieve.scala new file mode 100644 index 00000000..49d864ef --- /dev/null +++ b/numbers/Eratosthenes sieve/EratosthenesSieve.scala @@ -0,0 +1,21 @@ +/** + * Parse first parameter as number n and return list of all prime numbers less or equal n. + * Time complexity is O(N * log(log N)), memory complexity is O(N) + */ +object EratosthenesSieve extends App { + val n = Integer.valueOf(args(0)) + val primeNumbers = sieve(n) + println(primeNumbers.mkString(" ")) + + private def sieve(n: Int): Seq[Int] = { + val isPrime = Array.fill[Boolean](n + 1)(true) + + for (i <- 2 to math.sqrt(n).toInt if isPrime(i)) { + for (j <- i * i to n by i) { + isPrime(j) = false + } + } + + (2 to n).filter(isPrime) + } +}