java - Making a Sieve of Eratosthenes more efficient & printing values of a boolean array -



java - Making a Sieve of Eratosthenes more efficient & printing values of a boolean array -

for class assignment asked write code in java sieve of eratosthenes , code inefficient. doesn't take long run i'm there's room loop besides listing out did..

here's code:

public class test { public static boolean[] myarray() { boolean[] myarray = new boolean[100]; for(int = 1;i <100; i++) { if(i % 2 ==0) { myarray[i] = true; } if(i % 3 ==0) { myarray[i]= true; } if(i % 5 ==0) { myarray[i]= true; } if(i % 7 ==0) { myarray[i]= true; } if(i % 11 ==0) { myarray[i]= true; } } myarray[2]=false; myarray[3]=false; myarray[5]=false; myarray[7]=false; myarray[11]=false; homecoming myarray; } }

basically did set elements not prime numbers true..

so main 2 questions 1. there way implement loop create code shorter 2. how print off elements of array true (prime)

i hope helps. sieve long topic anyway:

public class test { public static boolean[] myarray(int max) { boolean[] myarray = new boolean[max+1]; // myarray[i] == false iff prime for(int = 2; i*i <= max; i++) // optimization: i*i not check repeated divisors { if (!myarray[i]) // if prime (int j=i+i; j <= max; j += i) // mark multiples not prime myarray[j] = true; } homecoming myarray; } public static void print(int[] myarray) { // print array 1 time computed (int i=2; i< myarray.length; ++i) if (!myarray[i]) system.out.println(i+" prime"); } }

p.s.: code not tested.

java arrays

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -