how to check if a number is even or not in python

129 Views Asked by At

I am attempting to make a collatz conjecture program, but I can't figure out how to check for even numbers this is my current code for it

    elif (original_collatz % 2) == 0:
        new_collatz = collatz/2

anyone have an idea how to check

i tried it with modulo but could figure out how it works, and my program just ignores this line, whole program: `

#collatz program
import time

collatz = 7
original_collatz = collatz
new_collatz = collatz

while True:
    if original_collatz % 2 == 1:
        new_collatz = (collatz * 3) + 1

    elif (original_collatz % 2) == 0:
        new_collatz = collatz/2

    collatz = new_collatz

    print(collatz)

    if collatz == 1:
        print('woo hoo')
        original_collatz += 1

    time.sleep(1)
2

There are 2 best solutions below

0
WIP On

The problem is not that "your program ignore the lines", it's that you test the parity of original_collatz which doesn't change.

  • You need to check the parity of collatz
  • You need to use integer division (//) when dividing by two or collatz will become a float.
  • You don't really need to use new_collatz as an intermediate, you could just overwrite collatz directly.

Here is a fixed sample:

# collatz program
import time

collatz = 7
original_collatz = collatz
new_collatz = collatz

while True:
    if collatz % 2 == 1:
        new_collatz = (collatz * 3) + 1

    else:
        new_collatz = collatz // 2

    collatz = new_collatz

    print(collatz)

    if collatz == 1:
        print('woo hoo')
        original_collatz += 1
        collatz = original_collatz

    time.sleep(1)
1
Andreas On

Working example:

import time

collatz_init = 7
collatz = collatz_init

while True:
    if collatz % 2 == 1:
        collatz = (collatz * 3) + 1
    else:
        collatz //= 2

    print(collatz)

    if collatz == 1:
        print('woo hoo')
        collatz_init += 1
        collatz = collatz_init

    time.sleep(1)