fork(6) download
  1. // code obtained from studyalgorithms.com
  2.  
  3. class SieveOfEratosthenes {
  4.  
  5. static void sieveOfEratosthenes(int n) {
  6.  
  7. // Create a boolean array "prime[0..n]" and initialize
  8. // all entries it as true. A value in isPrime[i] will
  9. // finally be false if i is Not a prime, else true.
  10.  
  11. boolean isPrime[] = new boolean[n + 1];
  12. for (int i = 0; i < n; i++)
  13. isPrime[i] = true;
  14.  
  15. for (int number = 2; number * number <= n; number++) {
  16.  
  17. // If prime[p] is true, then it is a prime number
  18. // we need to ignore it and now mark all it's multiples
  19. if (isPrime[number] == true) {
  20.  
  21. // Update all multiples of p
  22. for (int i = number * 2; i <= n; i += number)
  23. isPrime[i] = false;
  24. }
  25. }
  26.  
  27. // Print all prime numbers
  28. // At this point only the numbers which are set as true are prime.
  29. for (int i = 2; i <= n; i++) {
  30. if (isPrime[i] == true)
  31. System.out.print(i + " ");
  32. }
  33. }
  34.  
  35. public static void main(String[] args) {
  36.  
  37. sieveOfEratosthenes(30);
  38. }
  39. }
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
2 3 5 7 11 13 17 19 23 29