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)
CodePudding user response:
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 orcollatz
will become a float. - You don't really need to use
new_collatz
as an intermediate, you could just overwritecollatz
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)
CodePudding user response:
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)
CodePudding user response:
It seems that the prev. posts have pointed clearly your oringal problems.
Here is a simplified version to approach it, just for reference:
def collatz_sequence(x):
ans = [x]
if x < 1: return []
while x > 1:
if x & 1: # odd num
x = 3 * x 1
else: # even num
x //= 2
ans.append(x)
return ans
print(collatz_sequence(100))
# collatz_sequence(100)
[100, 50, 25, 76, 38, 19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]