14,028,229 members
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
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.

## 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.
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)

Top Experts
Last 24hrsThis month
 Gerry Schmitz 100 OriginalGriff 70 Michael Haephrati 64 Patrice T 44 Christian Graus 25
 OriginalGriff 2,641 Dave Kreskowiak 990 Patrice T 928 Maciej Los 846 Richard Deeming 773