Home > OS >  How many times x is divisible by y using function
How many times x is divisible by y using function

Time:05-26

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

CodePudding user response:

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

CodePudding user response:

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
  • Related