I'm writing a function in Python that tells us the greatest power of a number, that divides another number. I keep getting a ZeroDivisionError: float floor division by zero at Line 9. I'm not sure what to do to try and fix this error.
Any help or suggestions to fix my function are greatly appreciated!
def greatest_power_dividing(divisor,n):
if divisor == 0: #reason for float division error?
raise ValueError("Divisor cannot be zero.")
if divisor > n:
raise Error("divisor cannot be greater than number input")
power = 0
while n//(divisor**power) >= 1:
if n//divisor**power <n: #less than, then keep incrementing
power += 1
else:
power -= 1 #go back one power
return power
assert greatest_power_dividing(2, 8) == 3
assert greatest_power_dividing(3, 15) == 1
assert greatest_power_dividing(5, 15) == 1
assert greatest_power_dividing(5, 75) == 2
assert greatest_power_dividing(7, 75) == 0
So far to troubleshoot, I've tried changing / to // so that no floats are allowed. I have also tried raising a ValueError if the divisor equals 0 and another error if the divisor is greater than n (number being input by the user).
When I changed / to //, I started getting the float floor division error as well.
I think you messed up with this algorithm. It keeps decrement the power, so
has a limit of zero, and python catches dividing by it.
To fix it - you should define return point as a state when the second number is not divisible by the first. I.e.
n % divisor != 0