作为一个额外的任务,我们被要求找到产生最长collatz序列的10个起始数字(n)。 (其中0 < n < 10,000,000,000)我编写了代码来完成这个任务,但是我估计完整计算答案需要11个小时。
我注意到了一些小的优化,比如从大到小开始,因此添加到数组中的内容会减少,并且只在10,000,000,000/2^10(=9765625)和10,000,000,000之间进行计算,因为必须有10个更长的序列,但我看不到我还能做什么。 有人可以帮忙吗?
相关代码 序列搜索算法
我注意到了一些小的优化,比如从大到小开始,因此添加到数组中的内容会减少,并且只在10,000,000,000/2^10(=9765625)和10,000,000,000之间进行计算,因为必须有10个更长的序列,但我看不到我还能做什么。 有人可以帮忙吗?
相关代码 序列搜索算法
long[][] longest = new long[2][10]; //terms/starting number
long max = 10000000000l; //10 billion
for(long i = max; i >= 9765625; i--) {
long n = i;
long count = 1; //terms in the sequence
while(n > 1) {
if((n & 1) == 0) n /= 2; //checks if the last bit is a 0
else {
n = (3*n + 1)/2;
count++;
}
count++;
}
if(count > longest[0][9]) {
longest = addToArray(count, i, longest);
currentBest(longest); //prints the currently stored top 10
}
}
存储算法
public static long[][] addToArray(long count, long i, long[][] longest) {
int pos = 0;
while(count < longest[0][pos]) {
pos++;
}
long TEMP = count; //terms
long TEMPb = i; //starting number
for(int a = pos; a < longest[0].length; a++) {
long TEMP2 = longest[0][a];
longest[0][a] = TEMP;
TEMP = TEMP2;
long TEMP2b = longest[1][a];
longest[1][a] = TEMPb;
TEMPb = TEMP2b;
}
return longest;
}
/ 2
替换为>>> 1
。但这并不能带来太大的改善。 - Martijn Courteauxk
次迭代。https://en.wikipedia.org/wiki/Collatz_conjecture#Optimizations - Martijn Courteaux