Help with "n" primes algorithm in an Arraylist

Asked

Viewed 706 times

0

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

  • See how to find prime numbers in this question.

  • 2

    You can paste your code here instead of this image?

  • Thank you so much for your help and patience.

  • Good luck... :)

1 answer

1


Your contador++ is out of the while - this means that the code below will execute 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 solve this, use keys in the while loop and the for loop:

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

while() {
    // código aqui
}

Using your own code:

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

Using the @Victorstafusa response, follows a possible solution:

Java cousins.:

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

Numerointeger.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;
    }
}

Upshot:
lista de primos gerada pelo programa

  • Can you help me with the rest of the code? ,the method is just returning the number 2 20 times(when this. n = 20)

  • @Johnschultz saw the link I posted above?

  • Yes, it could help me how to fix my code using the names of my variables,is that seeing the code with other names and different methods has left me confused

  • @Johnschultz didn’t even touch the algorithm - it was copy&paste from the other answer - take a look at my issue.

Browser other questions tagged

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