About Me

My photo
#Engineer #Writer #Optimist #Traveler #PumpingIron

Sunday, February 14, 2010

EratosthenesSieve : A very fast algorithm for finding Prime numbers.


  1. /*
  2. * EratosthenesSieve.java
  3. *
  4. * Copyright 2010 Ankush Bisht
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  19. * MA 02110-1301, USA.
  20. */
  21. public class EratosthenesSieve {
  22. public static void main (String args[]) {
  23. System.out.println("Enter the Number till you want to print the Primes");
  24. int a[]=new int[new java.util.Scanner(System.in).nextInt()];
  25. for(int i=0;i<a.length;i++)
  26. a[i]=i+1;
  27. int i,j,k,step;
  28. for(i=1;i<a.length;i++)
  29. {
  30. if(a[i]!=0)
  31. {
  32. k=a[i]*2-1;
  33. step=a[i];
  34. for(j=k;j<a.length;j+=step)
  35. a[j]=0;
  36. }
  37. }
  38. System.out.println("Prime Numbers between 1 and "+a.length+" are: ");
  39. for(i=0;i<a.length;i++)
  40. {
  41. if(a[i]!=0)
  42. System.out.println(a[i]+" ");
  43. }
  44. }
  45. }

No comments:

Post a Comment