作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图通过使用迭代器迭代来从 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);
}
}
它会删除某些素数,但不会删除其他素数。谢谢你的帮助。我试图在主方法中完成这一切,而不需要类。
最佳答案
您的算法无法正确查找素数,因此有些被删除,有些则没有。
据我所知,您将 0 到 101 之间的 20 个随机数添加到列表中,其中有些是质数,有些不是。然后,您可以根据索引和列表中的第一个数字对索引 * 进行迭代并删除数字。
从表面上看,您正在尝试实现 Sieve of Eratosthenes但你还没有完全正确地理解。
粗略地说,您需要从 2 迭代到 101 的平方根,并从列表中删除每个的所有倍数。这可以作为两个 for
循环来实现。
(*) @Pelit Mamani 指出了关键点 - remove(i)
使用索引。
关于java - 如何从链表中删除素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33250500/
我是一名优秀的程序员,十分优秀!