Skip to content

Commit 3ff15c0

Browse files
BrianLusinaBrianLusina
authored andcommitted
feat(puzzles): calculate product of x and y using recursion
1 parent 6cbfd17 commit 3ff15c0

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Product of Two Positive Integers
2+
3+
Given two numbers, find their product using recursion. In Python, we usually use the * operator to multiply two numbers,
4+
but you have to use recursion to solve this challenge.
5+
6+
Hint:
7+
8+
```plain
9+
5 * 3 = 5 + 5 + 5 = 15
10+
```
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
def recursive_multiply(x: int, y: int) -> int:
2+
"""Uses recursion to find the product of x and y
3+
Args:
4+
x (int): first number
5+
y (int): second number
6+
Returns:
7+
int: result of multiplication
8+
"""
9+
# this cuts down the recursive calls
10+
if x < y:
11+
return recursive_multiply(y, x)
12+
if y == 0:
13+
return 0
14+
return x + recursive_multiply(x, y - 1)
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import unittest
2+
from . import recursive_multiply
3+
4+
5+
class RecursiveMultiplyTestCase(unittest.TestCase):
6+
def test_1(self):
7+
"""should return 15 from 5 and 3"""
8+
x = 5
9+
y = 3
10+
expected = x*y
11+
actual = recursive_multiply(x, y)
12+
self.assertEqual(expected, actual)
13+
14+
def test_2(self):
15+
"""should return 1000000 from 500 and 2000"""
16+
x = 500
17+
y = 2000
18+
expected = x*y
19+
actual = recursive_multiply(x, y)
20+
self.assertEqual(expected, actual)
21+
22+
if __name__ == '__main__':
23+
unittest.main()

0 commit comments

Comments
 (0)