我的 Euler Project 14 代码如下。我已经运行此代码超过 3 小时,输出结果似乎是无限的。当我测试单个数字如 11、27 时,它会快速输出 collatz 链号:14 和 111。但我不知道为什么它不能输出 1000000 个数的最大链数。
/*Problem 14
* The following iterative sequence is defined for the set of positive integers:
* n -> n/2 (n is even)
* n -> 3n + 1 (n is odd)
* Using the rule above and starting with 13, we generate the following sequence:
* 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
* It can be seen that this sequence (starting at 13 and finishing at 1) contains
* 10 terms. Although it has not been proved yet (Collatz Problem), it is thought
* that all starting numbers finish at 1.
*
* Which starting number, under one million, produces the longest chain?
*
* NOTE: Once the chain starts the terms are allowed to go above one million.
*/
package number;
public class LongestCollatzSequence {
public static int collatzNum(int n){
int count = 0;
while(n != 1){
if(n%2 == 0)
n = n/2;
else
n = 3*n + 1;
count++;
}
return count;
}
public static void main(String[] args) {
int max = 0;
for(int i = 10; i <= 1000000; i++){
if(collatzNum(i) > collatzNum(max))
max = i;
}
System.out.println(max);
}
}
此外,我转向for(int i = 10; i <= 1000000; i++)
,for(int i = 10; i <= 10; i++)
这么短的数字列表,它仍然一直在运行而没有输出。我的代码有什么问题?
这是另一个人的解决方案,rianjs.net代码是:
public class Problem014
{
public static void main(String[] args)
{
long begin = System.currentTimeMillis();
LinkedList<Long> list = new LinkedList<Long>();
long length = 0;
int res = 0;
for(int j = 10; j < 1000000; j++){
long i = j;
while (i != 1){
if (i % 2 == 0){
i /= 2;
list.add(i);
}
else{
i = (3 * i) + 1;
list.add(i);
}
}
if(list.size() > length){
length = list.size();
res = j;
}
list.clear();
}
long end = System.currentTimeMillis();
System.out.println(res+" with chain size: "+ length);
System.out.println(end-begin + "ms");
}
}
他的代码运行良好,我想知道为什么我的代码不能得到输出,这两种分辨率有什么区别?