Behold, the factorial

competitive python nptel

Question #

Find the factorial $n!$, of a positive integer $n$.
The factorial $n!$ is defined as: $$n! = \prod_{i=1}^{n}{i} = 1 \times 2 \times …\times n$$

Solution #

This is a fairly simple problem which can be trivially solved using loops.

fact = 1
for i in range(1, n+1):
	fact *= i


We can approach the same thing using recursion also, by exploiting the fact that $n! = n \times (n-1)!$.

def fact(n):
	if n > 1:
		return n*fact(n-1)
	return 1


Now coming to the main part, we can get our one-liner using the recursive approach.

def fact(n): return n*fact(n-1) if n > 1 else 1



Nothing yet.

Leave a reply