Files
cybr108/lab-05/exercise-18.py
T
2026-10-12 17:48:57 -04:00

22 lines
714 B
Python

"""
The Collatz conjecture states that if you start with any positive integer n, and if n is even, divide it by 2; if n is
odd, multiply it by 3 and add 1. Repeat the process. The sequence will always eventually reach 1. Write a program to
print this sequence for a given number.
"""
# set variable n to 6
n = 6
# Runs the loop until n = 1, signifying the end of the Collatz conjecture
while n != 1:
# print value of n plus a comma and space to print on the same line
print(n, end=", ")
# if n is even, halve n
if n % 2 == 0:
n = n // 2
# if n is odd, multiply by 3 and add one
else:
n = n * 3 + 1
# Prints final value for n, which should always be 1
print(n)