Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. private static List<Integer> primeSieve(int n) {
  2. List<Integer> primes = new ArrayList<>();
  3. // minFact[i] contains the minimum prime factor of i.
  4. int[] minFact = new int[n + 1];
  5. for (int i = 2; i <= n; i++) {
  6. if (minFact[i] == 0) {
  7. primes.add(i);
  8. minFact[i] = i;
  9. }
  10. // Find multiples of i where primes[j] is the minimum prime factor. This loop will go exactly once for each
  11. // composite number. How it works: given a number i with prime factorization p1*...*pn, where p1<=...<=pn,
  12. // we say that, for each prime p <= p1, the number i*p is composite with minimum prime factor p.
  13. // Why this gets to every number exactly once: the number p1*...*pn will be generated only by p2*...*pn.
  14. // That's because all of it's prime factors need to be higher than it.
  15. for (int j = 0; j < primes.size() && primes.get(j) <= minFact[i] && i * primes.get(j) <= n; ++j) {
  16. minFact[i * primes.get(j)] = primes.get(j);
  17. }
  18. }
  19. return primes;
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement