我正在研究 Project Euler 问题 14,但我不明白问题是什么。在程序运行大约 8 秒后,我不断收到运行时错误——可能是 ArrayList 变得太大,但我该如何避免这种情况呢?
import java.util.ArrayList;
public class Problem14
{
public static void main(String[] args)
{
ArrayList<ArrayList<Long>>listOfLists=new ArrayList<ArrayList<Long>>();
for (long c=2; c<1000000; c++)
{
ArrayList<Long>tempList=new ArrayList<Long>();
long h=c;
while (h!=1)
{
tempList.add(h);
if (h%2==0)
h/=2;
else
h=((3*h)+1);
}
tempList.add(1l);
listOfLists.add(tempList);
}
long maxLength=0;
long maxPos=0;
for (int currList=0; currList<listOfLists.size(); currList++)
{
long currLength=(listOfLists.get(currList).size());
if(currLength>maxLength)
{
maxLength=currLength;
maxPos=currList+1;
}
}
System.out.println("The longest sequence is "+maxLength+" numbers
long. Its position is "+maxPos);
}
}