题目 The following iterative sequence is defined for the set of positive integers: n n/2 (n is even) 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. |
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); } |