Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add EratosthenesSieve java and scala implementation #47

Merged
merged 1 commit into from
Oct 9, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions numbers/Eratosthenes sieve/EratosthenesSieve.java
Original file line number Diff line number Diff line change
@@ -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<Integer> primeNumbers = sieve(n);
primeNumbers.forEach(EratosthenesSieve::print);
}

private static List<Integer> sieve(int n) {
List<Integer> 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);
}
}
21 changes: 21 additions & 0 deletions numbers/Eratosthenes sieve/EratosthenesSieve.scala
Original file line number Diff line number Diff line change
@@ -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)
}
}