Skip to content

Commit

Permalink
feat(puzzles): calculate product of x and y using recursion
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianLusina authored and BrianLusina committed Nov 22, 2024
1 parent 6cbfd17 commit 3ff15c0
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
10 changes: 10 additions & 0 deletions puzzles/product_of_two_positive_integers/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Product of Two Positive Integers

Given two numbers, find their product using recursion. In Python, we usually use the * operator to multiply two numbers,
but you have to use recursion to solve this challenge.

Hint:

```plain
5 * 3 = 5 + 5 + 5 = 15
```
14 changes: 14 additions & 0 deletions puzzles/product_of_two_positive_integers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
def recursive_multiply(x: int, y: int) -> int:
"""Uses recursion to find the product of x and y
Args:
x (int): first number
y (int): second number
Returns:
int: result of multiplication
"""
# this cuts down the recursive calls
if x < y:
return recursive_multiply(y, x)
if y == 0:
return 0
return x + recursive_multiply(x, y - 1)
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import unittest
from . import recursive_multiply


class RecursiveMultiplyTestCase(unittest.TestCase):
def test_1(self):
"""should return 15 from 5 and 3"""
x = 5
y = 3
expected = x*y
actual = recursive_multiply(x, y)
self.assertEqual(expected, actual)

def test_2(self):
"""should return 1000000 from 500 and 2000"""
x = 500
y = 2000
expected = x*y
actual = recursive_multiply(x, y)
self.assertEqual(expected, actual)

if __name__ == '__main__':
unittest.main()

0 comments on commit 3ff15c0

Please sign in to comment.