【问题标题】:How to remove prime numbers from a linked list如何从链表中删除素数
【发布时间】:2015-10-21 03:37:55
【问题描述】:

我正在尝试通过使用迭代器对其进行迭代来从 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 方法中完成所有这些操作,而无需类。

【问题讨论】:

  • 您正在设置ListIterator 并且几乎不使用它。我建议您重新设计循环以使用迭代器,特别是它的 remove() 方法。

标签: java linked-list iterator primes


【解决方案1】:

您的算法没有正确寻找素数,因此有些被删除,有些则没有。

据我所知,您将 20 个介于 0 和 101 之间的随机数添加到您的列表中,其中一些是质数,一些不是。然后,您根据索引和列表中的第一个数字以索引*为模迭代并删除数字。

从表面上看,您正在尝试实现Sieve of Eratosthenes,但您没有完全正确。

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

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

【讨论】:

  • 添加到“dave”的正确建议,还请注意它有助于停止并考虑:我是否有兴趣测试数组 elementsindices ?最重要的是,由于 List.remove... remove(i) 删除索引 i 处的元素,而 remove((Integer)i) 删除值 'i 的第一个元素,它变得更加混乱' .
猜你喜欢
  • 2020-10-29
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多