When I try and run my code I get the following error:
Traceback (most recent call last):
File "/home/exal/PycharmProjects/pythonProject/main.py", line 9, in <module>
if powerOfTwoCheck(n) == True:
File "/home/exal/PycharmProjects/pythonProject/main.py", line 4, in powerOfTwoCheck
return (n & (n - 1)) == 0 and n > 0
TypeError: unsupported operand type(s) for &: 'float' and 'float'
50.0
This error only occcurs when I use the %
operator, everything else seems to function correctly when I remove it.
my code:
# Collatz conjecture in python
def powerOfTwoCheck(n):
return (n & (n - 1)) == 0 and n > 0
# If a number is a power of two then it will eventually lead to the 4-1 loop
n = 100
while True:
if powerOfTwoCheck(n) == True:
break
elif n%2 == 0: # checks if number is even
n = n / 2
print(n)
elif n % 2 != 0: # Checks if number is odd
n = (n * 3) + 1
print(n)
Why is it occuring and How would i fix it?
(sorry if this is formatted wrong or a bad question, I rarely use stack overflow)
It is because in this:
elif n%2 == 0: # checks if number is even
n = n / 2
it converts n into a float that give error you have to convert it into integer
end code will be
def powerOfTwoCheck(n):
return (n & (n - 1)) == 0 and n > 0
n = 100
while True:
if powerOfTwoCheck(n) == True:
break
elif n%2 == 0:
n = int(n / 2)
print(n)
elif n % 2 != 0:
n = (n * 3) + 1
print(n)
You can use:
elif n%2 == 0:
n = int(n / 2)
or
elif n%2 == 0:
n = (n // 2)