Searching longest chain in Collatz sequence in Java, loop not terminating
我要应用collatz序列并将其应用于1到10^6之间的所有数字,并返回需要达到1的最大链的数字。然而,我有一个问题,我的循环似乎不会在Eclipse中终止,我也不知道为什么,我甚至不能得到控制台中显示的所有打印,尽管我希望每一步都显示出来。
collatz序列按以下规则计算:
如果n是奇数,则下一个数字是n/2
如果n为偶数,则下一个数字为3n+1
这就是我目前为止所拥有的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | public static long collatz() { long res = 0; long n = 1; long count = 0; long largestCount = 0; long t = 0; for (long k = 1; k <= 20; k++) { n = k; while (n != 1) { if ((n % 2) == 0) { n = n / 2; count = count + 1; } else { n = (3 * n) + 1; count = count + 1; } if (count > largestCount) { largestCount = count; res = k; } } } System.out.println(res); return res; } |
在C或Visual Basic中使用biginteger而不是long
例如http://herbert-helling.de/vb_tests/
如果您阅读了我的解决方案,您可以看到为一组代码行所要做的工作编写注释是如何非常有用的,并使代码成为自文档。
尝试联机
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public static long collatz(int maxN) { long res = 0, n = 1, count = 0, largestCount = 0, t = 0; // for K in [1, max-N] for (long k = 1; k <= maxN; k++) { // reset count to zero n = k; count = 0; // count how many steps to get to 1 while (n != 1) { // n = collatz(n) n = (n%2==0 ? n/2 : (3*n)+1); count++; // count the step } // check for maximum count if (count > largestCount) { largestCount = count; res = k; } } return res; // return maximum solution } |
它运行,但它将始终打印上次测试的编号,因为您没有重置
我还将
我已经在while循环之后移动了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public static long collatz() { long res = 0; long n = 1; long count = 0; long largestCount = 0; long t = 0; for (long k = 1; k <= 20; k++) { n = k; count = 0; // start every sequence with count = 0 while (n != 1) { if ((n % 2) == 0) { n = n / 2; } else { n = (3 * n) + 1; } count = count + 1; } if (count > largestCount) { largestCount = count; res = k; } } System.out.println(res); return res; } |
号
您的代码应该正常运行。但是它没有工作代码。您正在检查条件,以查看while循环中当前的
如果你感兴趣的话,这是我写的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | final int number = 1000000; long sequenceLength = 0; long startingNumber = 0; long sequence; for (int i = 2; i <= number; i++) { int length = 1; sequence = i; while (sequence != 1) { if ((sequence % 2) == 0) { sequence = sequence / 2; } else { sequence = sequence * 3 + 1; } length++; } //Check if sequence is the best solution if (length > sequenceLength) { sequenceLength = length; startingNumber = i; } } System.out.println(startingNumber); |