Behold, the factorial

competitive python nptel

Question #

Find the factorial n!n!, of a positive integer nn.
The factorial n!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

print(fact)

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

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

print(fact(n))

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

print(fact(n))


Comments

Nothing yet.

Leave a reply