-1

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)
Random Davis
  • 6,662
  • 4
  • 14
  • 24
  • 2
    `n!=n%2` is not how you check if a number is divisible by 2. You want `n % 2 == 0`. Also this is the Collatz Conjecture. – Random Davis Sep 12 '22 at 22:59
  • Typo: it should be `3*n + 1` not `3*n + 2`. – DarrylG Sep 12 '22 at 23:02
  • 1
    You want `n=n//2` or `n \\= 2` (integer division)to keep numbers as integers. – DarrylG Sep 12 '22 at 23:04
  • @RandomDavis I am trying get one that is divisible by 2 and another one who multiplies, I wrote n!=n%2 because I thought it would give me n when its not divisible by 2. Sorry for the confusion. – Marcelo Zevallos Sep 12 '22 at 23:11
  • @MarceloZevallos if the answer helped and fixed your issue, please consider accepting it by clicking the checkmark – Ali Sep 15 '22 at 09:13

2 Answers2

0

First of all your formula of 3*n + 2 will lead to infinite loop. According your sample output, it needs to be 3*n + 1.

n = 12
while n >= 1:
    print(n, end=' ')

    if n == 1:
        break

    if n % 2 == 0:
        n = n // 2
    else:
        n = 3 * n + 1
0

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

Ali
  • 439
  • 1
  • 4
  • 14