MCPcopy Create free account
hub / github.com/subbarayudu-j/TheAlgorithms-Python / collatz_sequence

Function collatz_sequence

project_euler/problem_14/sol2.py:1–13  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

1def 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
15answer = max([(len(collatz_sequence(i)), i) for i in range(1,1000000)])
16print("Longest Collatz sequence under one million is %d with length %d" % (answer[1],answer[0]))

Callers 1

sol2.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected