简体   繁体   中英

Find if a number is divisible by another number using recursion

How would I check if a number is divisible by another using recursion in python?

This is my code so far, but I would like to make it recursive.

def is_divisable(num, div):
    if num % div == 0:
        return True
    else:
        False

For educational purposes, you could keep subtracting until you reach 0 or below:

def is_divisible(num, div):
    while(num > 0):
        num -= div
    return num == 0

Using this logic you can make it recursive (Thanks to Anonymous for pointing out the above version is not recursive):

def is_divisible(num, div):
    if (num == 0):
        return True
    elif (num < 0):
        return False
    return is_divisible(num-div, div)

However, the correct way would be:

def is_divisible(num, div):
    return num % div == 0
def is_divisable(num,div):
    if num<div:
        return num %div==0
    else:
        return is_divisable(num-div,div)

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