Longest Collatz sequence
Longest Collatz sequence
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.
1.函数递归调用
1 | /*思路:简单递归 |
注意:方法1递归步数太多导致出现爆栈(segmentation fault),原因是递归调用太深
2.利用记忆数组优化递归过程
1 |
|
补充:当算法优化到极致时,只能是用空间换时间 or 用时间换空间,而记忆化数组就是典型的用空间换时间
http://polaris-hzn8.github.io/2023/03/01/algorithm/kkbalgorithmI/1.euler/5.Longest Collatz sequence/
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.