Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Method: sieveOfEratosthenes
- * This method takes a boolean array
- * This method changes all non-prime numbers up to the length of the array to false
- *
- * This method is by far one of the most difficult we have had so far
- *
- * A boolean array is like a row of light switches.
- * For this method they all should start up, ON, or true
- * If a light switch is ON, then the number is prime.
- * Your code should start at the number 2, and turn all 2's off
- * It should then go to 3 and turn all 3's off.
- * It should then go to 4 and turn all 4's off (you can skip this if you want)
- * etc.
- *
- * To find out how many elements are in an array, you use the array name, a period
- * and the keyword length.
- *
- */
- public static boolean[] sieveOfEratosthenes(boolean [] a){
- //Turn off, or set to false, all array spots that are not prime.
- //Yes, this is a double for loop, or a for loop inside a for loop
- //You will really need to think about this. Just dropping in numbers won't do it
- //Remember for loops have 3 important things. A starting point, and ending point,
- //and an increment. You can change all 3 items.
- //You may want to figure out the inside for loop first, i.e. get it to remove all
- //the 2's. Then wrap a for loop around that and make the inside for loop more
- //general
- for(int i=0; i<a.length(); i++)
- a[i]=true;
- for(int i = 2; i<a.length(); i++){
- if(a[i]){
- for(int j=i; j*i<a.length; j++)
- {
- a[j*i]=false;
- }
- }
- }
- return a;
- }
- }
Add Comment
Please, Sign In to add comment