Back to questions
Given a number , write a formula that returns .
In case you forgot the factorial formula, .
For example, so we'd return 120.
Assume is is a non-negative integer.
p.s. if this problem seems too trivial, try the follow-up Microsoft interview problem Factorial Trailing Zeroes
Here's an iterative solution, that runs through every number 1 to n, and multiplies it to a running answer.
**For extra credit, can you solve this problem recursively? **
Not just at Microsoft, but at other tech companies too, they typically ask you to solve a question using multiple approaches.
Here's our recursive solution:
In case you aren't familiar with recursion, we typically have two elements to a recursive function:
In this specific case, the recursive call is that the
However, you can see how this would end poorly, because we could keep going and going and going, making successively smaller till .
That's why we need a base case – something to terminate the recursion.
For this problem, the base case is that , which translate into Python is: