pythonrecursionfizzbuzz

Finding multiples using recursion


Given 1 to 100 numbers, for multiples of 3 it should print "he" ,for multiples of 5 it should print "llo" ,for both multiples of 3 and 5 it should print "hello".

This is what I have:

for i in range (1,100):
if(i%3==0):
    print("he")
elif(i%5==0):
    print("llo")
elif(i%3==0 and i%5==0):
    print("hello")

How would I do this recursively?


Solution

  • How about the code below?

    def find_multiples(current, last_num=100):
    
        # Base Case
        if current > last_num:
            return
    
        result = ""
    
        if current % 3 == 0:
            result += "he"
    
        if current % 5 == 0:
            result += "llo"
    
        if result:
            print(f"{current}: {result}")
    
        find_multiples(current+1, last_num)
    
    find_multiples(1)
    

    Base case is if current reaches last_num or the maximum number you'd like to check.