Results 1 to 4 of 4

Thread: Prime numbers

Threaded View

  1. #1

    Thread Starter
    Fanatic Member x-ice's Avatar
    Join Date
    Mar 2004
    Location
    UK
    Posts
    671

    Resolved Prime numbers

    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.
    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)
    }
    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:
    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]);    
        }
    }
    Any help would be great. Thanks.
    Last edited by x-ice; Feb 25th, 2007 at 07:26 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width