fork(3) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. System.out.println(generate(50));
  13. }
  14.  
  15. static ArrayList<Integer> generate(int n)
  16. {
  17. ArrayList<Integer> multiples = new ArrayList<>(), primes=new ArrayList<>(n);
  18. primes.add(2);
  19. multiples.add(2);
  20. for (int candidate = 3;
  21. primes.size() < n;
  22. candidate += 2
  23. ) {
  24. if (isPrime(candidate,multiples, primes))
  25. primes.add(candidate);
  26. }
  27. return primes;
  28. }
  29.  
  30. static boolean isPrime(int candidate, ArrayList<Integer> multiples, ArrayList<Integer> primes)
  31. {
  32. int nextPrime = primes.get(multiples.size()-1);
  33. if (candidate == nextPrime * nextPrime) {
  34. multiples.add(candidate);
  35. return false;
  36. }
  37. for (int n = 1; n < multiples.size(); n++) {
  38. int multiple = multiples.get(n);
  39. while (multiple < candidate)
  40. multiple += 2 * primes.get(n);
  41. multiples.set(n, multiple);
  42. if (candidate == multiple)
  43. return false;
  44. }
  45. return true;
  46. }
  47.  
  48. }
Success #stdin #stdout 0.06s 32464KB
stdin
Standard input is empty
stdout
[2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]