Skip to content

Commit dbe3f06

Browse files
SandersLinpoyea
authored andcommitted
Project Euler Problem 14 Solution 2 (TheAlgorithms#651)
1 parent d689b4b commit dbe3f06

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

project_euler/problem_14/sol2.py

+16
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)