Advertisement
kshuvo96

Sieve of Eratosthenes

Feb 5th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.96 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Scanner;
  3.  
  4. public class more_Optimised_Eratosthenes_sieve {
  5.  
  6.     static final int M = 1000000;
  7.     static boolean[] mark;
  8.    
  9.     public static void main(String[] args) {
  10.         ArrayList<Integer> primeList = new ArrayList<>();
  11.         Scanner scan = new Scanner(System.in);
  12.        
  13.         int n = scan.nextInt();
  14.         mark = new boolean[M];
  15.        
  16.         // call the Eratosthenes sieve.
  17.         sieveEra(n);
  18.        
  19.         for(int i = 1; i <= n; i++)
  20.             if(isPrime(i))
  21.                 primeList.add(i);
  22.        
  23.         System.out.println(primeList);
  24.        
  25.         scan.close();
  26.     }
  27.  
  28.     private static boolean isPrime(int n)
  29.     {
  30.         if(n < 2)
  31.             return false;
  32.         if(n == 2)
  33.             return true;
  34.         if(n % 2 == 0)
  35.             return false;
  36.        
  37.         return mark[n] == false;
  38.     }
  39.  
  40.     private static void sieveEra(int n)
  41.     {
  42.         for(int i = 3; i*i <= n; i += 2)   // run upto sqrt(n)
  43.         {
  44.             if(mark[i] == false)
  45.             {
  46.                 for(int j = i*i; j <= n; j += 2*i)
  47.                     mark[j] = true;                
  48.             }                                    
  49.         }
  50.     }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement