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.
Not just at Microsoft, but at other tech companies too, interviewers ask you to solve a question using multiple approaches – or at least mention the different alternatives.
Here's a recursive solution to computing factorials:
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 translated into Python is: