Collatz conjecture: start with any positive integer n.Next termis obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture states the seq
(n)
| 1 | def collatz_sequence(n): |
| 2 | """Collatz conjecture: start with any positive integer n.Next termis obtained from the previous term as follows: |
| 3 | if the previous term is even, the next term is one half the previous term. |
| 4 | If the previous term is odd, the next term is 3 times the previous term plus 1. |
| 5 | The conjecture states the sequence will always reach 1 regaardess of starting n.""" |
| 6 | sequence = [n] |
| 7 | while n != 1: |
| 8 | if n % 2 == 0:# even |
| 9 | n //= 2 |
| 10 | else: |
| 11 | n = 3*n +1 |
| 12 | sequence.append(n) |
| 13 | return sequence |
| 14 | |
| 15 | answer = max([(len(collatz_sequence(i)), i) for i in range(1,1000000)]) |
| 16 | print("Longest Collatz sequence under one million is %d with length %d" % (answer[1],answer[0])) |