1

I am trying to remove the prime numbers from a LinkedList by iterating over it using an Iterator. I have the following code

import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Random;

public class LinkedListProcesing{
    public static void main(String[] args){

    int listSize = 0;
    LinkedList<Integer> list = new LinkedList<Integer>();
    Random randNumGen = new Random();

    while(listSize<20){
        int nextRand = randNumGen.nextInt(101); //while there are less than 20 random ints process a new one
        list.add(nextRand); //add the new random number to the linked list
        //System.out.println(nextRand);
        listSize+=1; //iterate over the list size
    }

    System.out.println("The list contains these 20 random integers: " + list);

    ListIterator iterator = list.listIterator();
    int next = (Integer) iterator.next();

    for (int i=2; i<list.size(); i++){
        if (i>=1){
            list.remove(i);
        }
        if (next%i!=0){
            list.remove(i);
        }
    }

    System.out.println("This is the list excluding primes: " + list);
}

}

It removes certain primes but not others. Thanks for any help. I am trying to do this all in the main method as well with no need for classes.

jcvandam
  • 57
  • 1
  • 1
  • 3
  • You are setting up a `ListIterator` and hardly using it. I suggest that you rework your loop to use the iterator, specifically its `remove()` method. – rossum Oct 21 '15 at 12:21

1 Answers1

2

Your algorithm does not look for primes correctly, hence some are removed and some are not.

From what I can see, you add 20 random numbers between 0 and 101 to your list, of which some will be prime and some not. You then iterate through and remove numbers based on the index and the first number in the list modulo the index*.

By the looks of it, you're trying to implement the Sieve of Eratosthenes but you haven't got it quite right.

Roughly speaking, you need to iterate from 2 up to the square root of 101, and remove all multiples of each from your list. This could be implemented as two for loops.

(*) @Pelit Mamani nails the key point - remove(i) uses the index.

Community
  • 1
  • 1
dave
  • 11,641
  • 5
  • 47
  • 65
  • 1
    Adding to "dave's" correct advice, please also note it helps to stop and consider: am I interested in testing array *elements* or *indices* ? To top that, it becomes even more confusing because of the ambiguity of List.remove... remove(i) removes the element at index i, while remove((Integer)i) removes the first element of value 'i' . – Pelit Mamani Oct 21 '15 at 05:28