如何从链表中删除素数

时间:2015-10-21 03:37:55

标签: java linked-list iterator primes

我试图通过迭代使用Iterator从LinkedList中删除素数。我有以下代码

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);
}

}

它删除了某些素数而不是其他素数。谢谢你的帮助。我试图在main方法中完成所有操作,不需要类。

1 个答案:

答案 0 :(得分:2)

你的算法没有正确地查找质数,因此有些被删除而有些则没有。

从我所看到的,你可以在你的列表中添加0到101之间的20个随机数,其中一些将是素数而另一些则不是。然后,您可以根据索引和列表中第一个以索引*为模的数字来迭代并删除数字。

从它的外观来看,你正试图实现Sieve of Eratosthenes,但你还没有完全正确。

粗略地说,你需要从2迭代到101的平方根,并从列表中删除每个的所有倍数。这可以实现为两个for循环。

(*)@Pelit Mamani指出关键点 - remove(i)使用索引。

相关问题