Question from Daily Coding Problem 210 as reproduced below:
A Collatz sequence in mathematics can be defined as follows. Starting with any positive integer:
if n is even, the next number in the sequence is n / 2 if n is odd, the next number in the sequence is 3n + 1 It is conjectured that every such sequence eventually reaches the number 1. Test this conjecture.
Bonus: What input n <= 1000000 gives the longest sequence?
My code (note that it is incomplete):
def collatz(n): sequenceLength = 0 while (n>=1): if (n==1): break # solution is found elif (n%2==0): n = n/2 sequenceLength += 1 else: n = 3*n+1 sequenceLength += 1 return(sequenceLength) def longest_seq(limit): result = [] for i in range(1, limit+1): result += [collatz(i)] print(result) return max(result) Question: In this case, I need to test the conjecture that I will always reach "1" for all positive integers. However, my code above assumes this which means I could potentially run an infinite loop.
What is a good/elegant method to test the conjecture? I was thinking something along the lines of a cache/array to see if values of "n" are repeated at the beginning of the while loop. If so, it suggests an infinite loop. However, I am a bit stuck on the syntax part and not clear on the examples I've seen so far. I just need a way to: - Add things to a cache/equivalent - Check whether something exists within the cache/equivalent (and this either gives me a proper return or an elegant invalid response that I can use, without crashing my program)
Much thanks.
n/2ton//2. In Python 2 they're the same, but in Python 3/will convert to floating point, while//will give you integer division, which is what you want.