Skip to content

Commit 9c0cbe3

Browse files
SandersLinpoyea
authored andcommitted
Create collatz_sequence.py (#639)
* Create collatz_sequence.py * Update and rename collatz_sequence.py to maths/collatz_sequence.py * doctest
1 parent 7b267e5 commit 9c0cbe3

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Diff for: maths/collatz_sequence.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
def collatz_sequence(n):
2+
"""
3+
Collatz conjecture: start with any positive integer n.Next termis obtained from the previous term as follows:
4+
if the previous term is even, the next term is one half the previous term.
5+
If the previous term is odd, the next term is 3 times the previous term plus 1.
6+
The conjecture states the sequence will always reach 1 regaardess of starting n.
7+
Example:
8+
>>> collatz_sequence(43)
9+
[43, 130, 65, 196, 98, 49, 148, 74, 37, 112, 56, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
10+
"""
11+
sequence = [n]
12+
while n != 1:
13+
if n % 2 == 0:# even
14+
n //= 2
15+
else:
16+
n = 3*n +1
17+
sequence.append(n)
18+
return sequence
19+
20+
21+
def main():
22+
n = 43
23+
sequence = collatz_sequence(n)
24+
print(sequence)
25+
print("collatz sequence from %d took %d steps."%(n,len(sequence)))
26+
27+
if __name__ == '__main__':
28+
main()

0 commit comments

Comments
 (0)