Advertisement
MattPlummer

Untitled

Oct 25th, 2014
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. class PrimeSieve {
  2. public static void main(String[] args) {
  3. int N = Integer.parseInt(args[0]);
  4.  
  5. // initially assume all integers are prime
  6. boolean[] isPrime = new boolean[N + 1];
  7. for (int i = 2; i <= N; i++) {
  8. isPrime[i] = true;
  9. }
  10.  
  11. // mark non-primes <= N using Sieve of Eratosthenes
  12. for (int i = 2; i*i <= N; i++) {
  13.  
  14. // if i is prime, then mark multiples of i as nonprime
  15. // suffices to consider mutiples i, i+1, ..., N/i
  16. if (isPrime[i]) {
  17. for (int j = i; i*j <= N; j++) {
  18. isPrime[i*j] = false;
  19. }
  20. }
  21. }
  22.  
  23. // count primes
  24. int primes = 0;
  25. for (int i = 2; i <= N; i++) {
  26. if (isPrime[i]){ primes++; System.out.print(i+", ");}
  27. }
  28. System.out.println("\nThe number of primes <= " + N + " is " + primes);
  29. }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement