Help with algorithm of "n" prime numbers in an ArrayList

0

Please, I need urgent help, how to fix my code? every time I call the right error method, I'm a beginner and I'm locked in an exercise that requires prime numbers based on a number n (in this case this.n), for example the number is 20, it should return one ArrayList with the first 20 prime numbers (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71) of the code using for-each

    
asked by anonymous 30.05.2017 / 06:28

1 answer

1

Your contador++ is out of while - this means that the following code will run forever :

contador++; // estou fora do while!
while(contador < this.n) // contador sempre será menor que this.n
    aux.add(i); // acaba com a memória heap adicionando i em aux eternamente

To resolve this, use keys in the while loop and in the for loop:

for (;;) {
    // código aqui
}

while() {
    // código aqui
}

Using your code:

while(contador < this.n) {
    aux.add(i);
    contador++; // agora contador eventualmente será maior que this.n
}
  

Using the response from @VictorStafusa , a possible solution follows:

Primos.java:

public class Primos {
    public static void main(String[] args) {
        NumeroInteiro n = new NumeroInteiro(20);
        for (int i : n.getPrimos()) {
            System.out.print(i + " ");
        }
    }
}

Numero.java:

import java.util.ArrayList;

public class NumeroInteiro {
    private int n = 0;

    public NumeroInteiro(int n) {
        this.n = n;
    }

    public ArrayList<Integer> getPrimos() {

        ArrayList<Integer> aux = new ArrayList<Integer>();
        for (int i = 1; aux.size() < this.n; i++) {
            int counter = 0;
            for (int k = 1; k <= i; k++) {
                if (i % k == 0)
                    ++counter;
            }
            if (counter == 2) {
                aux.add(i);
            }
        }
        return aux;
    }
}

Result:

    
30.05.2017 / 07:09