Float Division by Zero Error with Function Telling Greatest Power of a Number Dividing Another Number

86 Views Asked by At

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.

2

There are 2 best solutions below

0
dmgzh On

I think you messed up with this algorithm. It keeps decrement the power, so

(divisor**power) 

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

0
President James K. Polk On

divisor**power is always a float when power is negative, as it is in your code. As power gets more and more negative it eventually reaches -1075 at which point divisor**power is evaluated as 0.0. The smallest power you should consider is 0 or 1 depending on what your goal is. Basically, you need new logic in your code.

Here is a copy of your code with a different loop to find the greatest power.

def greatest_power_dividing(divisor, n):
    if divisor == 0:  # reason for float division error?
        raise ValueError("Divisor cannot be zero.")

    if divisor > n:
        raise ValueError("divisor cannot be greater than number input")

    power = 0
    while n % divisor == 0:
        n //= divisor
        power += 1
    return power