We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent d689b4b commit dbe3f06Copy full SHA for dbe3f06
project_euler/problem_14/sol2.py
@@ -0,0 +1,16 @@
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]))
0 commit comments