forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Project Euler Problem 14 Solution 2 (TheAlgorithms#651)
- Loading branch information
1 parent
d689b4b
commit dbe3f06
Showing
1 changed file
with
16 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
def collatz_sequence(n): | ||
"""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 sequence will always reach 1 regaardess of starting n.""" | ||
sequence = [n] | ||
while n != 1: | ||
if n % 2 == 0:# even | ||
n //= 2 | ||
else: | ||
n = 3*n +1 | ||
sequence.append(n) | ||
return sequence | ||
|
||
answer = max([(len(collatz_sequence(i)), i) for i in range(1,1000000)]) | ||
print("Longest Collatz sequence under one million is %d with length %d" % (answer[1],answer[0])) |