We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent c3b8c51 commit 8fe553dCopy full SHA for 8fe553d
collatz_sequence.py
@@ -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