Guest User

Untitled

a guest
May 26th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1.     /**
  2.      * Method: sieveOfEratosthenes
  3.      * This method takes a boolean array
  4.      * This method changes all non-prime numbers up to the length of the array to false
  5.      *
  6.      * This method is by far one of the most difficult we have had so far
  7.      *
  8.      * A boolean array is like a row of light switches.
  9.      * For this method they all should start up, ON, or true
  10.      * If a light switch is ON, then the number is prime.
  11.      * Your code should start at the number 2, and turn all 2's off
  12.      * It should then go to 3 and turn all 3's off.
  13.      * It should then go to 4 and turn all 4's off (you can skip this if you want)
  14.      * etc.
  15.      *
  16.      * To find out how many elements are in an array, you use the array name, a period
  17.      * and the keyword length.
  18.      *
  19.      */
  20.     public static boolean[] sieveOfEratosthenes(boolean [] a){
  21.        
  22.         //Turn off, or set to false, all array spots that are not prime.
  23.         //Yes, this is a double for loop, or a for loop inside a for loop
  24.         //You will really need to think about this.  Just dropping in numbers won't do it
  25.         //Remember for loops have 3 important things.  A starting point, and ending point,
  26.         //and an increment.  You can change all 3 items.
  27.        
  28.         //You may want to figure out the inside for loop first, i.e. get it to remove all
  29.         //the 2's.  Then wrap a for loop around that and make the inside for loop more
  30.         //general
  31.         for(int i=0; i<a.length(); i++)
  32.             a[i]=true;
  33.        
  34.         for(int i = 2; i<a.length(); i++){
  35.             if(a[i]){
  36.                 for(int j=i; j*i<a.length; j++)
  37.                 {
  38.                     a[j*i]=false;
  39.                 }
  40.         }
  41.        
  42.         }
  43.        
  44.         return a;
  45.     }
  46.  
  47.  
  48. }
Add Comment
Please, Sign In to add comment