# -*- coding: utf-8 -*- """ Created on Sun Apr 07 01:10:52 2013 @author: Matthew Cordrey """ #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. def collatz(x): terms = 1 termsList = [x] while x > 1: if x % 2: x = 3*x+1 else: x = x/2 termsList.append(x) terms += 1 return terms chains = {} for i in range(1000001): chains[i] = collatz(i) analysis = sorted(chains.items(), key=lambda k: k[1], reverse=True) print "\nThe Winner >>>>> Start Number: ",analysis[0][0], " | Chain Length: ",analysis[0][1]
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question