fork download
  1. import java.util.Iterator;
  2.  
  3. final class Ideone {
  4.  
  5. private static Iterable<Integer> primes(final int n) {
  6. final boolean[] composite = new boolean[n+1];
  7. for (int i = 2; i <= n; ++i) {
  8. if (!composite[i]) {
  9. for (int j = i * i; j <= n; j += i) {
  10. composite[j] = true;
  11. }
  12. }
  13. }
  14. return new Iterable<Integer>() {
  15.  
  16. public Iterator<Integer> iterator() {
  17. return new Iterator<Integer>() {
  18. int cur = 1;
  19.  
  20. public Integer next() {
  21. while (cur <= n && composite[cur++]) ;
  22. return cur - 1;
  23. }
  24.  
  25. public boolean hasNext() {
  26. int p = cur;
  27. while (p <= n && composite[p++]) ;
  28. return p <= n;
  29. }
  30. };
  31. }
  32. };
  33. }
  34.  
  35. public static void main(final String[] argv) {
  36. for (final int p : primes(100)) {
  37. System.out.println(p);
  38. }
  39. }
  40. }
Success #stdin #stdout 0.1s 320320KB
stdin
Standard input is empty
stdout
1
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97