Created
February 13, 2018 08:39
-
-
Save MohanSha/424bd512fb021f6d3d60682a5dd11172 to your computer and use it in GitHub Desktop.
The Factorial of a positive integer, n, is defined as the product of the sequence n, n-1, n-2, ...1 and the factorial of zero, 0, is defined as being 1. Solve this using both loops and recursion.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Factorial Finder | |
# The Factorial of a positive integer, n, is defined as the product of the | |
# sequence n, n-1, n-2, ...1 and the factorial of zero, 0, is defined as | |
# being 1. Solve this using both loops and recursion. | |
def factorial(n): | |
result = 1 | |
if n == 0: | |
return result | |
while n > 0: | |
result *= n | |
n -= 1 | |
return result | |
def factorial_rec(n): | |
if n == 0: | |
return 1 | |
else: | |
return n * factorial_rec(n-1) | |
def main(): | |
n = 5 | |
result = factorial_rec(n) | |
print result | |
result = factorial(n) | |
print result | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment