fork(2) download
  1. import java.io.*;
  2. import java.util.*;
  3. class Simple //print prime numbers <=N. O(N loglogN). Eratosthenes
  4. {
  5. public static void main(String args[]) throws IOException
  6. {
  7.  
  8. int N;
  9. long i,j;
  10.  
  11. System.out.println("Enter N");
  12. N=Integer.parseInt(br.readLine().trim());
  13.  
  14. long start=System.nanoTime();
  15. boolean a[]=new boolean [N+1];
  16. Arrays.fill(a,true);
  17.  
  18. a[0]=false;
  19. a[1]=false;
  20.  
  21. for(i=2;i<=N;i++)
  22. {
  23. if(a[(int)i]==true)
  24. {
  25. for(j=i*i;j<=N;j+=i)
  26. a[(int)j]=false;
  27. }
  28. }
  29.  
  30. long end=System.nanoTime();
  31. double ans=((double)(end-start))/1000000000;
  32. System.out.println("\nTime in seconds:");
  33. System.out.println(ans+"\n");
  34. System.out.println("Primes less than N :");
  35. //for(i=2;i<=N;i++)
  36. //{
  37. // if(a[(int)i]==true)
  38. // System.out.print(i+" ");
  39. // }
  40. }
  41. }
Success #stdin #stdout 0.12s 38156KB
stdin
10000000
stdout
Enter N

Time in seconds:
0.068977386

Primes less than N :