Print prime values contained in an array

Asked

Viewed 418 times

-1

I can’t get the prime numbers that are inside this List4 array; I’ve tried several ways, but without success. Currently, my code looks like this:

List<Integer> list8 = new ArrayList<>();
    int numPrimo = 0;
            int numDivisores = 0;
            for (int i = 1; i <= list4.size(); i++) {
                if (numPrimo % i == 0) {
                    numDivisores++;
                }
                if(numDivisores == 2) {
                    list8.add(numDivisores);
                }
            }
            sysout("10) Os números primos entre as duas listas são: " + list8);

I need a light

1 answer

0


You need to do a for to list all the elements of the list 4 and, within that, create a new loop to check if the number in question is a prime number (increasing the number of divisors). After this second loop, you can check if the number of divisors is equal to 2, ie if the number is prime. Follow the code:

public static void main(String[] args) {

    List<Integer> list8 = new ArrayList<Integer>();
    List<Integer> list4 = new ArrayList<Integer>();

    for(int i = 0; i < 10; i++) {
        list4.add(i);
    }

    int numDivisores = 0;

    for (Integer numPrimo : list4) {
        for (int i = 1; i <= numPrimo; i++) {
            if (numPrimo % i == 0) {
                numDivisores++;
            }
        }

        if (numDivisores == 2) {
            list8.add(numPrimo);
        }
        numDivisores = 0;
    }

    System.out.println("10) Os números primos entre as duas listas são: " + list8);
}
  • 1

    Thanks, it worked super well and still cleared me a bigger doubt!

  • Not at all, and I’m glad he helped you.

Browser other questions tagged

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