pythoncollatz

How do I make it so it can loop?


I need to test whether n is a multiple of 2 and then divide the number by 2. If the number isn't a multiple of 2, then I have to do 3*n+2.

How do I make it loop so I can get the following: 12, 6, 3, 10, 5, 16, 8, 4, 2, 1?

Here's my current code:

n=12
while n!=0:
    if n%2==0:
        print (n)
    n=n/2
    if n!=n%2:
        if n !=1:
            n = 3*n+2
    else:
        break
print(n)

Solution

  • First note is that it is 3*n+1, second one is that you have to write n=n/2 in your first if.

    Overall this code is what you want:

    n = 12
    while n != 0:
      if n % 2 == 0:
        print(n, end=' ')
        n = n / 2
        
      elif n % 2 != 0:
        if n != 1:
            print(n, end=' ')
            n = 3 * n + 1   
        else:
            print(1)
            break
    

    Or this:

    n = 12
    while n > 1:
      if n % 2 == 0:
        print(n, end=' ')
        n = n / 2
    
      elif n % 2 != 0:
        if n != 1:
            print(n, end=' ')
            n = 3 * n + 1   
        else:
            print(1)
    

    Good luck