Python练习题 042:Project Euler 014:最长的考拉兹序列
本题来自 Project Euler 第14题:https://projecteuler.net/problem=14
''' Project Euler: Problem 14: 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. Answer: 837799(共有525个步骤) ''' import time startTime = time.clock() def f(x): c = 0 #计算考拉兹序列的个数 while x != 1: if x%2 == 0: #若为偶数 x = x//2 c += 1 else: #若为奇数 x = x*3+1 c += 1 if x == 1: c += 1 #数字1也得算上 return c chainItemCount = 0 startingNumber = 0 for i in range(1, 1000000): t = f(i) if chainItemCount < t: chainItemCount = t startingNumber = i print('The number %s produces the longest chain with %s items' % (startingNumber, chainItemCount)) print('Time used: %.2d' % (time.clock()-startTime))
互动百科说了,考拉兹猜想--又称为3n+1猜想、角谷猜想、哈塞猜想、乌拉姆猜想或叙拉古猜想,是指对于每一个正整数,如果它是奇数,则对它乘3再加1,如果它是偶数,则对它除以2,如此循环,最终都能够得到1。
判断条件很清楚,所以解题思路也很清晰:把 1-999999 之间的所有数字都拿来判断,计算每个数字分解到1所经历的步骤数,拥有最大步骤数的那个数字(Starting Number)即为解。
解这题,我的破电脑花了29秒。我隐约感觉这题应该有更好的解法,比如我很不喜欢的递归之类的……