Click here to Skip to main content
14,028,229 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
def mult(a, b):
if b == 1:
return a
else:
return a + mult(a, b-1)

print(mult(2, 4))

What I have tried:

I have tried to understand how come this code does a multiplication without having a multiplication operator with no success.
Posted
Updated 15-Aug-18 0:53am
v2
Comments
digimanus 15-Aug-18 6:35am
   
why didn't you debug?
Member 13949923 15-Aug-18 7:00am
   
"I've tried putting bunch of prints but it still doesn't show me how it does multiplication without a multiplication operator." Edit: I just got it why.

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Recursion is simple to understand: see "recursion" and it'll all be clear!

Your function calls itself with different parameters, and return to itself with the value each time when it's calculated.
Look at what happens with your code when you pass specific values: a == 2, b == 3
1) 2, 3 : b is not 1, so you call the function again, with a == 2, b == 2
1.1) 2, 2 : b is not 1, so you call the function again, with a == 2, b == 1
1.1.1) 2, 1 : b is one, so you return a: 2
1.2) returns to 2, 2: and returns the 2 you got from 1.1.1, plus 2 : 4
2) returns to 2, 3: and returns the 4 you got from 1.2, plus 2 : 6

So the whole function returns 6.

It's a poor example of recursion - a loop is a lot easier and more efficient - but just follow it through with a debugger, and you'll see what I mean.
   
Comments
Member 13949923 15-Aug-18 7:36am
   
Thank you for the great answer. I think I get it now. Correct me if I am wrong. Basically, the multiplication process is taking through the parameter 'a' being added to the result of the 'mult(a, b-1)' by an recursive action since 'mult(a, b-1)' is a smaller function inside of its own greater mirror function def 'mult(a, b)'.
OriginalGriff 15-Aug-18 8:28am
   
Forget the terms "smaller function" and "mirror function" - it's the same function being called recursively.

Think about it: multiplication is repetitive addition:
x * y = x + x + x ... x + x
where there are "y x's" on the right have side:
4 * 3 = 4 + 4 + 4
7 * 2 = 7 + 7
That's all your recursive function is doing: subtracting one to provide a count of how many times it needs to call itself.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web05 | 2.8.190419.4 | Last Updated 15 Aug 2018
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100