Created
May 9, 2014 18:05
-
-
Save vidia/54c560f5b04be51e812b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#Non-recursive | |
def Main(): | |
n=eval(input("n?") | |
fact = 1 | |
for i in range(n,1,-1): | |
fact=fact*i | |
print("The factorial of",n,"is:", fact) | |
# Recursive | |
def fact(n): | |
#end condition | |
if n == 1: | |
return 1 | |
else: | |
return n*fact(n-1) | |
I'm curious as to how we go from fact=fact*i to carry out the calculating factorial function (without recursion) to getting it to carry out the same calculation with recursion with n*fact(n-1). If you could explain the logic that would be great. I don't understand how those two lines of code both carry out the same mathematical function. | |
In the first solution, the counting is handled by a loop and there is a "running total" that is constantly stored in 'fact'. This allows the loop to count up only one number at a time and keep multiplying it onto the total so far. | |
This "running total" in the recursive solution is handled a little differently. In the recursive, the total of each "sub-facrotial" is returned to the parent function which uses that to calsulate the larger factorial. | |
So in the first solution the factorial goes (assumong 5!) | |
I have 5, okay lets start there. | |
The next number is 4, so I have 20 now. | |
The next number is 3, so I have 60. | |
etc. | |
In the recursive solution it is slightly different. (again with 5!) | |
I have to take a factorial of 5. Well I don't know how to do that, but I might be able to do a factorial of 4. | |
Okay so let me take out the 5 and try to do the factorial of 4. | |
I still can't do it, so I'l try fact(3) | |
then fact(2) | |
finally fact(1) | |
I KNOW HOW TO DO THIS! (And it returns 1 stopping the recursion) | |
The "1" is passed back to the parent version of fact() (the one that was called as fact(2)) and the "1" is multiplied by the 2 that was taken out. | |
That solution is passed back up to its parent (the fact(3)) and is multiplied by 3 there. | |
And so on... | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment