Problem: Compute factorial of a number. The factorial of non-negative number, n, is the product of all positive integers less than or equal to n.
Example:
Factorial of 0 is 1.
Factorial of 1 is 1.
Factorial of 2 is 2.
Factorial of 3 is 6.
Factorial of 4 is 24.
Factorial of 5 is 120.
Solution in Python:
def factorial(n):
"""
Author: Mayur P Srivastava
"""
assert n >= 0
result = 1
for i in range(n):
result *= i+1
print "Factorial of %d is %d" % (n, result)
Concepts learned: Single loop.
No comments:
Post a Comment