Topic from Project Euler 14th: https://projecteuler.net/problem=14
"Project Euler:problem 14:longest Collatz sequencethe following iterative sequence are defined for the set of positive INTEGERS:N→N/2 (n is even) n→3n + 1 (n was odd) Using the rule above and starting with a, we generate the following sequ Ence:13→40→20→10→5→16→8→4→2→1it can seen that this sequence (starting at and finishing at 1) contai NS Ten terms. Although it has not been proved yet (Collatz problem), it's thought, all starting numbers finish at 1.Which starting n Umber, under one million, produces the longest chain? Note:once The chain starts the terms is allowed to go above one million. answer:837799 (total of 525 steps) "Import Timestarttime = 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 cchainitemcount = 0startingNumber = 0for i in range (1, 1000000): T = f (i) If CHAinitemcount < T:chainitemcount = T StartingNumber = iprint (' The number%s produces the longest chain WI Th%s Items '% (StartingNumber, chainitemcount)) print (' Time used:%.2d '% (Time.clock ()-starttime))
Interactive Encyclopedia said that Cauraz conjecture--also known as 3n+1 conjecture, Angular Valley conjecture, Hasse conjecture, Ulam conjecture, or the "idea of"--is that for every positive integer, if it is odd, it is multiplied by 3 plus 1, and if it is an even number, divide it by 2, so that the loop will eventually get 1.
The judging condition is very clear, so the problem-solving mentality is also very clear: to judge all the numbers between 1-999999, calculate the number of steps to decompose each number to 1, the number with the largest number of steps (starting numbers) is the solution.
To solve this problem, my broken computer took 29 seconds. I vaguely feel that the problem should have a better solution, such as I do not like recursion and so on ...
Python exercises 042:project Euler 014: Longest Cauraz sequence