For a coursework assignment i must implement the 'Sieve of Eratothenes' on a sorted array of number and then place all the prime numbers in an ArrayList. (I am using Java).
Here is the psuedo code algorithm.And here is my Java code, but it doesn't work. I don't know what is wrong with it, it just hangs (possible infinate loop somewhere).Code:Eratosthenes(n) { a[1] := 0 for i := 2 to n do a[i] := 1 p := 2 while p2 < n do { j := p2 while (j < n) do { a[j] := 0 j := j+p } repeat p := p+1 until a[p] = 1 } return(a) }Any help would be great. Thanks.Code:public void sievePrimes() { numbers[0] = 0; int n = 100; for(int i=1; i<n; i++) { numbers[i] = 1; } int p = 2; while(p*p <= n) { int j = p*p; while(j <= n) //Error is possibly here, infinate loop! { numbers[j-1] = 0; j = j+p; } while(numbers[p] != 1) { p++; } } for(int index=0; index < numbers.length; index++) { System.out.println(numbers[index]); } }




Reply With Quote