简体   繁体   中英

How many times x is divisible by y using function

So, basically I have to built an algorithm that tells me how many times X is divisible by Y. If its not divisible, it should return print -1.

Here's what i've got so far:

def divisible(x, y):
 n = int(x/y)
 if (n != 0 and x%y == 0):
   print(x, "its divisible by",y,n,"times")
 else:
    print(-1)

divisible(5, 2)

The exercise its asking to use a counter to do this. How can I make It?

Thanks

Integer division and the modulo function should get you there -

divisible = lambda x, y: x // y if x % y == 0 else -1
divisible(13, 3)
# -1
divisible(12, 3)
# 4
def divisible (x, y):
    # Initialize times to keep track of how many times x is
    # divisible by y:
    times = 0
    # Enter an infinite loop:
    while True:
        # If the remainder of x divided by y is 0
        # (= if x is divisible by y):
        if ( x % y == 0 ):
            # Increment times by 1 and actually divide x by y:
            times += 1
            x = x / y
        # If x is *not* divisible by y, break out of the infinite loop:
        else:
            break
    # If the original x was not divisible by y at all, return -1
    # (otherwise, keep times unchanged):
    if times == 0:
        times = -1
    return times
    
print(divisible(2, 2))
# 1

print(divisible(3, 2))
# -1

print(divisible(8, 2))
# 3

print(divisible(10000, 2))
# 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM