/** * This class performs Erathostenes sieve method, * please refer to COSC229 tutorial 5 (4) * * @author Sharon Duan * @version Oct 2007 */ public class Sieve { private int n; private int[] a; /** * Constructor for objects of class Sieve */ public Sieve(int n) { this.n = n; a = new int[n+1]; } public void sieveout() { int i=2; // start with sieving by 2 while(i*i<=n){ // when i<=sqrt(n) for(int x=i+1; x<=n; x++){ // for each x where i+1<=x<=n if(x%i==0) a[x]=1; // set x as a composite if x=0 mod i } i++; // increase i } printPrimes(); } private void printPrimes() { System.out.println("n = " + n); for(int j=2; j<=n; j++){ if(a[j]==0) System.out.println(j); } } public void setN(int n) { this.n = n; a = new int[n+1]; } }