Question

I've got some trouble with the sieve of eratosthenes. So i've got the mathmatics calculations for the sieve from a book called "Schaum's outlines" but i think the book has programmed to code wrong... This is the code from the book:

public class Sieve
{
    final static int P = 800;
    static boolean[] isPrime = new boolean[count];

Sieve();
{
    for (int i = 2; i<P; i++)
    {
        isPrime[i] = true;
    }
    for (int i = 2; i<P/2; i++)
    {
        if (isPrime[i])
        {
            for (int j = 2*i; j<P; j += i)
            {
                isPrime[j] = false;
            }
        }   
    }
}
public static void main(String[] args)
{
    new Sieve();
    print();
}

static void print()  {
    for (int i=0; i<count; i++)
        if (isPrime[i]) System.out.println(i + " ");
        else if (i%90==0) System.out.println();
        System.out.println();
}}

So yeah i used the code and made some slight changes due to the fact that "Sieve()" isn't recognized. Here below is my code:

public class Primenumbers
{
    final static int count = 1000;
    static boolean[] isPrime = new boolean[count];

    public static sieve(int count, boolean isPrime);
    {
        for (int i = 2; i<count; i++)
        {
            isPrime[i] = true;
        }
        for (int i = 2; i<count/2; i++)
        {
            if (isPrime[i])
            {
                for (int j = 2*i; j<count; j += i)
                {
                    isPrime[j] = false;
                }
            }   
        }
    }
    public static void main(String[] args)
    {
        for (int i=0; i<count; i++)
        {
            if (isPrime[i])
            {
                System.out.println(i + " ");
            }
        }
    }
}

So... what am i doing wrong? Thanks for the help!

Was it helpful?

Solution

what am i doing wrong?

You have defined sieve() but you never call it. You need to call it before printing:

public static void main(String[] args)
{
    sieve(); // <<== Here
    for (int i=0; i<count; i++)
    {
        if (isPrime[i])
        {
            System.out.println(i + " ");
        }
    }
}

The reason it worked in the book was that the initialization has been done in the constructor. Your modified code moved the initialization into a static function, but it fails to call that initialization.

You also need to remove parameters from the declaration of sieve, because it already has access to isPrime and count.

An alternative is to remove the sieve method altogether, replacing it with a static initializer. Instead of

public static sieve() 
{
    // Code to initialize isPrime
}

write

static
{
    // Code to initialize isPrime
}

This change makes sieve() method a static initializer, which is always called before anything else in your class gets to execute.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top