fork download
  1. //WARNING: SLOWER THAN SIMPLE SIEVE IN PRACTICE!
  2.  
  3. /* Sieve of Eratosthenes marks some number "false" more than once
  4.  * For example, 45 is marked false when i=3 as well as when i=5
  5.  * With this sieve, we only mark each composite numbers false once
  6.  * Thus this is faster
  7.  * This is exactly 2*N. N numbers are being visited and N numbers are being marked exactly once
  8.  * Number of primes less than or equal to N is approx N/lnN
  9.  */
  10. import java.io.*;
  11. import java.util.*;
  12. class OrderN //SLOWER IN PRACTICE, but FASTER IN THEORY
  13. {
  14. public static void main(String args[]) throws IOException
  15. {
  16.  
  17. int N;
  18. long i,j,count=0;
  19.  
  20. System.out.println("Enter N");
  21. N=Integer.parseInt(br.readLine().trim());
  22.  
  23. long start=System.nanoTime();
  24.  
  25. boolean isprime[]=new boolean[N+1];
  26. int prime[]=new int[N/((int)Math.log(N)-1)];
  27. //int SPF[]=new int[N+1]; //stores smallest prime factor of i
  28.  
  29. Arrays.fill(isprime,true);
  30.  
  31. isprime[0]=false;
  32. isprime[1]=false;
  33.  
  34. for(i=2;i<=N;i++)
  35. {
  36. if(isprime[(int)i]==true)
  37. {
  38. prime[(int)(count++)]=(int)i;
  39. //SPF[(int)i]=(int)i;
  40. }
  41.  
  42. for(j=0;j<count&&(i*prime[(int)j])<=N;j++)
  43. {
  44. isprime[(int)(i*prime[(int)j])]=false;
  45. if(i%prime[(int)j]==0)
  46. break;
  47. }
  48. }
  49.  
  50. long end=System.nanoTime();
  51.  
  52. double ans=((double)(end-start))/1000000000;
  53. System.out.println("\nTime taken in seconds");
  54. System.out.println(ans+"\n");
  55.  
  56. System.out.println("Prime numbers less than N :");
  57. //for(i=0;i<count;i++)
  58. //System.out.print(prime[(int)i]+" ");
  59. }
  60. }
Success #stdin #stdout 0.21s 41028KB
stdin
10000000
stdout
Enter N

Time taken in seconds
0.150200922

Prime numbers less than N :