[英]Java, out of memory, inefficient function
I'm writing a program that is supposed to create chains of numbers and see witch one is the longest. 我正在编写一个程序,该程序应该创建数字链,并且看到其中一个最长。 The problem is that I run out of memory and I have no idea what eats all of the memory.
问题是我的内存用完了,不知道是什么占用了所有的内存。 Does anyone know were the problem is?
谁知道是问题所在?
public static void main(String[] args) {
ArrayList<Integer> longestchain;
ArrayList<Integer> chain = new ArrayList<Integer>();
int size = 0;
int longestsize = 0;
int start;
int number = 0;
for(int i = 3; i < 1000000; i++)
{
start = i;
chain.clear();
chain.add(start);
size = 1;
while(true)
{
if(start == 1)
{
break;
}
if(iseven(start))
{
start = start / 2;
}
else
{
start = start*3 + 1;
}
chain.add(start);
size++;
}
if(size > longestsize)
{
longestsize = size;
longestchain = chain;
number = i;
}
//System.out.println(i);
}
System.out.println(number + ". " + longestsize);
}
public static boolean iseven(int n)
{
return (n % 2 == 0);
}
The problem is that when i=113383
you're running into an integer overflow. 问题是,当
i=113383
您将遇到整数溢出。 This results in an infinite loop that keeps adding to chain
until you run out of heap space. 这将导致一个无限循环不断增加
chain
,直到用完堆空间。 Change chain
and longestchain
to ArrayList<Long>
, start
to long
and iseven()
to take long
, and you'll solve that particular problem. 将
chain
和longestchain
更改为ArrayList<Long>
, start
为long
, iseven()
花费long
,您将解决该特定问题。
Another problem is that longestchain = chain
assigns the reference, whereas you need to copy the contents. 另一个问题是
longestchain = chain
分配了引用,而您需要复制内容。 Otherwise the next iteration will wipe longestchain
. 否则,下一次迭代将擦除
longestchain
。
This will probably not be the solution, but a hint: 这可能不是解决方案,而是提示:
The default array size for an ArrayList is 10. Initialize your ArrayLists to a value closer to what you are expecting, or many array creations happen under the hood: ArrayList的默认数组大小为10。将ArrayList初始化为一个更接近您期望值的值,否则将在后台进行许多数组创建:
// e.g.
ArrayList<Integer> chain = new ArrayList<Integer>(50000);
Don't know why are you running out of memory, but I noticed a bug in your code - longestchain and chain point to the same object, so when you clear chain, you also clear longestchain. 不知道为什么内存不足,但是我注意到您的代码中有一个错误-longestchain和chain指向同一对象,因此当您清除链时,您也会清除longestchain。 You can fix it by creating a new array with contents of chain instead of an assignment.
您可以通过创建一个具有链内容而不是分配内容的新数组来修复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.