Search code examples
pythonsequencecollatz

Collatz sequence


How can I take an integer as input, of which the output will be the Collatz sequence following that number. This sequence is computed by the following rules:

  • if n is even, the next number is n/2
  • if n is odd, the next number is 3n + 1.

e.g. when starting with 11

11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

This is my code now:

n = int(raw_input('insert a random number'))

while n > 1:
    if n%2 == 0:
        n_add = [n/2]
        collatz = [] + n_add
    else:
        n_add2 = [3*n + 1]
        collatz = [] + n_add2 
        print collatz

if I execute this and insert a number, nothing happens.


Solution

  • You are never changing the number n, so it will be the same each time round. You are also only printing if the number is odd. Also, square brackets [] indicate an array - I'm not sure what your goal is with this. I would probably rewrite it like this:

    n = int(raw_input('insert a random number'))
    
    while n > 1:
        if n%2 == 0:
            n = n/2
        else:
            n = 3*n + 1
        print n
    

    You might want to take some time to compare and contrast what I'm doing with your instructions - it is almost literally a word-for-word translation (except for the print

    It is a little unclear from your code if you want to just print them out as they come out, or if you want to collect them all, and print them out at the end.