1

I have a function that prints the first multiples of a number (n) starting with zero and stopping at num_multiples, but it keeps printing out one too many multiples. I'm hoping someone can explain what I'm doing wrong so I can understand recursion a bit more.

def print_first_multiples(n, num_multiples):    
    if num_multiples < 0:
        return
    else:
        print_first_multiples(n, num_multiples - 1)
        print(n * num_multiples, end=' ') 

for example, passing 5 as n and 10 as num_multiples, it should print: 0 5 10 15 20 25 30 35 40 45

but is instead printing an extra "50" at the end.

1
  • Why do you think its an extra 50 you print every time num_multiples is greater than 0 and you start it at 10 so it will print 5 * 10 which is 50 Commented Dec 3, 2022 at 17:02

3 Answers 3

1

First, 0 is not a multiple of 5. The first multiple of 5 is 5 (5*1). The problem with your code is that you only stop when num_multiples is negative (less than 0). Instead, you want to stop when it is zero. Like this:

def print_first_multiples(n, num_multiples):    
    if num_multiples == 0:
        return
    else:
        print_first_multiples(n, num_multiples - 1)
        print(n * num_multiples, end=' ')


print_first_multiples(5, 10)

If you do want to start at 0 and go up to 45, then you can subtract one from num_multiples. Like this:

def print_first_multiples(n, num_multiples):    
    if num_multiples == 0:
        return
    else:
        print_first_multiples(n, num_multiples - 1)
        print(n * (num_multiples-1), end=' ')


print_first_multiples(5, 10)
Sign up to request clarification or add additional context in comments.

1 Comment

0 is a multiple of 50 (every number) by most definitions (en.wikipedia.org/wiki/Multiple_(mathematics))
0

Try if num_multiples <= 0: instead

1 Comment

That still wouldnt give the expected result the user listed
0

It prints until it doesn't enter if num_multiples < 0. So e.x. with the initial value num_multiples = 3 you print for num_multiples=3, num_multiples=2, num_multiples=1, and num_multiples=0 so 4 times. Replace if num_multiples < 0 with if num_multiples == 0 and you'd get what you expect

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.