2020-02-06 21:00:08 +00:00
|
|
|
from typing import List
|
|
|
|
|
|
|
|
|
|
|
|
def collatz_sequence(n: int) -> List[int]:
|
2019-08-01 15:54:03 +00:00
|
|
|
"""
|
2020-02-06 21:00:08 +00:00
|
|
|
Collatz conjecture: start with any positive integer n. The next term is
|
|
|
|
obtained as follows:
|
|
|
|
If n term is even, the next term is: n / 2 .
|
|
|
|
If n is odd, the next term is: 3 * n + 1.
|
|
|
|
|
|
|
|
The conjecture states the sequence will always reach 1 for any starting value n.
|
2019-08-01 15:54:03 +00:00
|
|
|
Example:
|
2020-02-06 21:00:08 +00:00
|
|
|
>>> collatz_sequence(2.1)
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
Exception: Sequence only defined for natural numbers
|
|
|
|
>>> collatz_sequence(0)
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
Exception: Sequence only defined for natural numbers
|
2020-05-22 06:10:11 +00:00
|
|
|
>>> collatz_sequence(43) # doctest: +NORMALIZE_WHITESPACE
|
|
|
|
[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]
|
2019-08-01 15:54:03 +00:00
|
|
|
"""
|
2020-02-06 21:00:08 +00:00
|
|
|
|
|
|
|
if not isinstance(n, int) or n < 1:
|
|
|
|
raise Exception("Sequence only defined for natural numbers")
|
|
|
|
|
2019-08-01 15:54:03 +00:00
|
|
|
sequence = [n]
|
|
|
|
while n != 1:
|
2020-02-06 21:00:08 +00:00
|
|
|
n = 3 * n + 1 if n & 1 else n // 2
|
2019-08-01 15:54:03 +00:00
|
|
|
sequence.append(n)
|
|
|
|
return sequence
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
n = 43
|
|
|
|
sequence = collatz_sequence(n)
|
|
|
|
print(sequence)
|
2020-02-06 21:00:08 +00:00
|
|
|
print(f"collatz sequence from {n} took {len(sequence)} steps.")
|
2019-08-01 15:54:03 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2019-08-01 15:54:03 +00:00
|
|
|
main()
|