| 题目 The following iterative sequence is defined for the set of positive integers: n Using the rule above and starting with 13, we generate the following sequence: 13
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. |
public static int collatzProblem(long n) {
// counter
int count = 1;
// loop until n equals 1
while (n != 1) {
if (n % 2 == 0) {
n /= 2;
} else {
n = 3 * n + 1;
}
count++;
}
return count;
}
public static void main(String[] args) {
// test
// max: current longest chain length
// index: which number has the longest chain till now.
long max = 1, index = 1;
for (long i = 1; i <= 1000000; i++) {
int temp = collatzProblem(i);
if (temp > max) {
max = temp;
index = i;
}
}
System.out.println(max + "/t" + index);
} |
Problem 14 - Find the longest sequence using a starting number under one million.
本文探讨了Collatz猜想,通过定义迭代序列并计算从任意正整数开始直至1的最长链长度。采用Java实现,寻找小于一百万的最大起始数字,该数字产生的序列长度最长。

被折叠的 条评论
为什么被折叠?



