Skip to content

Commit 8fe553d

Browse files
authored
Create collatz_sequence.py
1 parent c3b8c51 commit 8fe553d

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

collatz_sequence.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
16+
def main():
17+
n = 43
18+
sequence = collatz_sequence(n)
19+
print(sequence)
20+
print("collatz sequence from %d took %d steps."%(n,len(sequence)))
21+
22+
23+
24+
if __name__ == '__main__':
25+
main()

0 commit comments

Comments
 (0)