Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Scanner;
- public class more_Optimised_Eratosthenes_sieve {
- static final int M = 1000000;
- static boolean[] mark;
- public static void main(String[] args) {
- ArrayList<Integer> primeList = new ArrayList<>();
- Scanner scan = new Scanner(System.in);
- int n = scan.nextInt();
- mark = new boolean[M];
- // call the Eratosthenes sieve.
- sieveEra(n);
- for(int i = 1; i <= n; i++)
- if(isPrime(i))
- primeList.add(i);
- System.out.println(primeList);
- scan.close();
- }
- private static boolean isPrime(int n)
- {
- if(n < 2)
- return false;
- if(n == 2)
- return true;
- if(n % 2 == 0)
- return false;
- return mark[n] == false;
- }
- private static void sieveEra(int n)
- {
- for(int i = 3; i*i <= n; i += 2) // run upto sqrt(n)
- {
- if(mark[i] == false)
- {
- for(int j = i*i; j <= n; j += 2*i)
- mark[j] = true;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement