Reputation: 479
Can anyone tell me what's wrong with the code below? I wanted to print all prime numbers smaller then 41 but it prints also 15, 21 which are not prime.
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int x = 41;
List<Integer> lista = new ArrayList<Integer>();
for (int i = 1; i<=x; i++){
lista.add(i);
}
System.out.println(lista);
for (int i = 0; i<lista.size()-1; i++){
if (!isPrime(lista.get(i))){
lista.remove(lista.get(i));
}
}
System.out.println(lista);
}
public static boolean isPrime(int x){
boolean itIs = true;
for (int i = 2; i < x; i++){
if(x%i == 0){
itIs = false;
}
}
return itIs;
}
}
Upvotes: 2
Views: 4744
Reputation: 393936
When you remove an element from an ArrayList, you change the indices of the rest of the ArrayList, so your loop skips some of the numbers.
One possible fix is to decrement the counter of the loop after removing an element from the List :
for (int i = 0; i<lista.size()-1; i++){
if (!isPrime(lista.get(i))){
lista.remove(lista.get(i));
i--;
}
}
A better solution would be to add the found prime numbers to a new List while keeping the original List unchanged.
Upvotes: 3