Search code examples
pythonintcollatz

Print the collatz sequence of a positive int, n, one value per line stoping at 1 using python


I've done:

def collatz(n):
    seq = n
    if n == 1:
        n = n
    while n > 1:
       if n % 2 == 0:
           n = n // 2
       else:
           n = 3 * n + 1
    print(seq)

The corrct output for calling this function, while n = 10:

collatz(10)
10
5
16
8
4
2
1

But the only number printed is n itself.


Solution

  • The issue is that you are only printing seq which was set to n at start of the function, after the while loop has executed. Hence you only get the value printed once.

    You should print the value inside the while loop as well as at start (for the first 10 print). Example -

    def collatz(n):
        print(n)
        while n > 1:
           if n % 2 == 0:
               n = n // 2
           else:
               n = 3 * n + 1
           print(n)
    

    Demo -

    >>> def collatz(n):
    ...     print(n)
    ...     while n > 1:
    ...        if n % 2 == 0:
    ...            n = n // 2
    ...        else:
    ...            n = 3 * n + 1
    ...        print(n)
    ...
    >>> collatz(10)
    10
    5
    16
    8
    4
    2
    1