Problem with Eratosthenes sieve - JAVA

Asked

Viewed 843 times

3

My teacher passed the following class for implementation of the Eratosthenes sieve, but gave very vague instructions on how we should do it, although he made it very clear that we should only touch the methods getPrimes() and findPrimes() and not in the rest of the code.

Could someone help me find a solution to this exercise?

Follow the code as per my best attempt at resolution:

package javaapplication1;

/**
 * Essa classe encontra numeros primos pelo metodo do
 * crivo de Eratostenes
 * 
 * @see java.lang.Object
 * @author 
 * @version 1.0
 */
public class Sieve
{   
    /** 
     * numero de primos encontrados
     */
    private int count = 0;

    /** 
     * arrays de primos (true se o numero i na posicao [i] eh primo)
     */
    private boolean[] primes;

    /**
     * O construtor define a quantidade maxima de numeros primos que serao
     * gerados pelo crivo de Eratostenes
     * 
     * @param size Define numero entre 0 e size-1 serao verificados 
     *             se sao primos ou nao
     */
    public Sieve(int size) 
    {
        primes = new boolean[ size ];
        // assumir, inicialmente, que todos numeros sao primos
        for ( int index = 0; index < primes.length; index++ )
        {   
            primes[ index ] = true;
        }
        // encontrar os numeros primos
        findPrimes();
    }

    /**
     * @return o numero de primos encontrados
     */
    public int getCount()
    {
        return count;
    }

    /**
     * @return array contendo true para os numeros que sao primos
     */
    public boolean [] getPrimes()
    {   // sua implementacao vem aui...
          return primes;
    }

    /**
     * Encontra primos pelo metodo do crivo de Eratostenes.
     * Ao final do metodo, o array primes contem true apenas para os 
     * numeros primos e count contem o numero de primos encontrados.
     */
    private void findPrimes()
    {   // sua implementacao vem aui...
             for(int i = 2; i <=primes.length; i++){
        if(primes[i]){
            for(int j = i; i*j <= primes.length; j++)
                primes[i*j] = false;
        }
    }
    }

    public static void main( String[] args )
    { 
      Sieve s = new Sieve( 16 );
      boolean[] p = s.getPrimes();
      for ( int index = 2; index < p.length; index++ )
         if ( p[ index ] )
            System.out.printf( "%d eh primo.\n", index );
      System.out.printf( "\n%d primos encontrados.\n", s.getCount() );
   } // end main

} // end class Sieve
  • Take a look at this link https://pt.wikipedia.org/wiki/Crivo_de_Erat%C3%B3stenes Try to implement the instructions in the findPrimes() method. In the getPrimes method vc only returns the array with the prime numbers found.

  • @Wagnersoares I’m getting Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException after implementing the code, edited in the original post

  • Could someone explain to me why this question was closed? For me it is perfectly clear. It is true that the original version had some problems that would even justify the first closing votes, but the way it is now (and was so before receiving the last closing vote) seems ok to me.

1 answer

4


Your algorithm is almost right. You just made a silly mistake in findPrimes():

         for(int i = 2; i <=primes.length; i++){
        for(int j = i; i*j <= primes.length; j++)

In those two ties, it was to use the < instead of <=. Exchanging both for <, your algorithm works and lists the prime numbers.

The algorithm works until you use new Sieve(46349). If you use new Sieve(46350) or a higher number, hence the algorithm fails due to overflow.

There is also the problem that in the end, the algorithm always shows this:

0 cousins found.

This is because nowhere are you putting one count++.

  • 1

    Hello, I’d like to thank you for your help! I just added count++ in the loop of findPrimes() and it all worked out. Again, thank you!

  • @Leonardofelixdasilva If my answer has served, do not forget to mark it as accepted/correct by clicking on the side of the answer.

  • @Victorstafusa Instead of going up primes.length, can’t go to the square root of it? I haven’t looked at the problem in detail, but usually to find a cousin I make a loop that starts with i=2 while i<=Math.sqrt(numero).

  • 1

    @eightShirt No. In the standard algorithm of successive divisions you would certainly do this, but this is not the algorithm here. The Erasmus sieve does not work like that, because in it you start with a list of all the numbers in the desired range, assuming that all numbers are initially primes and will elicit from that list the numbers that are multiples of other numbers. Note that the successive division algorithm looks for divisors while the Erasthenes sieve looks for multiples.

  • Copy that. Got it, thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.