我正在编写此 Java 程序以使用埃拉托色尼筛法查找最多 num 个素数,但是当我尝试编译时,它说我不能使用 long var 作为数组索引,它期望一个int var 取而代之。但我将处理大量数字,所以我不能使用 int。我能做什么?
import java.util.*;
import java.lang.*;
public class t3{
public static void main(String[] args){
long num = 100;
//declaring list and filling it with numbers
ArrayList<Long> numlist = new ArrayList<Long>();
for(long x=2 ; x<num ; x++){
numlist.add(new Long(x));
}
//sieve or eratosthenes
for(long x=0 ; x<Math.sqrt(num) ; x++){
for(long y=x+1 ; y<numlist.size() ; y++){
if(numlist[y]%numlist[x] == 0){
numlist.remove(y);
}
}
}
//print list
for(Object item : numlist){
System.out.println((Long)item);
}
}
}
最佳答案
我不确定为什么您的代码会首先编译。
您不应该在数组列表中使用 [] 来访问成员。 arraylist 只是一个内部存储在数组中的列表。您必须使用列表获取操作(仍然是 O(1))。写 numlist[index] 意味着你在 numlist 中有一个对象数组。您不能像在 C++ 中那样覆盖 [] 操作。
另外,在Java中int是32位的。长度大于 2^32 的数组(因此您需要长索引)是不太可能的,我什至不确定规范是否允许。
关于java - 在 java 中使用 long as ArrayList 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/459643/