Editor

Multiply by Adding

#568 · Functions · Beginner · 35 XP · about 5 min

A calculator's times key is broken, but the plus key still works. Write a recursive function multiply(a, b) that returns a times b using only addition:

  • anything times 0 is 0,
  • otherwise, a times b is a plus a times b - 1.

A recursive function calls itself, each time on a smaller problem, until it reaches a case it can answer straight away (here b == 0).

Examples

multiply(4, 3)   # returns 12
multiply(7, 0)   # returns 0
multiply(-2, 5)  # returns -10

4 times 3 is 4 + (4 times 2), which is 4 + 4 + (4 times 1), which is 4 + 4 + 4 + (4 times 0) = 12.

Note

a can be any whole number. b is a whole number from 0 to 500.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.