Skip to content

Instantly share code, notes, and snippets.

@hltbra
Created November 22, 2012 19:56
Show Gist options
  • Select an option

  • Save hltbra/4132707 to your computer and use it in GitHub Desktop.

Select an option

Save hltbra/4132707 to your computer and use it in GitHub Desktop.
fatorial com tail recursion optimization
def fat(n):
if n == 0:
result = 1
else:
result = n * fat(n - 1)
return result
"""
fat(5)
5 * fat(4)
5 * (4 * fat(3))
5 * (4 * (3 * fat(2)))
5 * (4 * (3 * (2 * fat(1)))
5 * (4 * (3 * (2 * (1 * fat(0)))
5 * (4 * (3 * (2 * (1 * 1))
5 * (4 * (3 * (2 * 1))
5 * (4 * (3 * 2))
5 * (4 * 6)
5 * 24
120
"""
def fat(n, acc=1):
if n == 0:
return acc
else:
return fat(n - 1, acc * n)
"""
fat(5, 1)
fat(4, 5)
fat(3, 20)
fat(2, 60)
fat(1, 120)
fat(0, 120)
120
"""
# print fat(1000)
from optimization import tail_recursion
@tail_recursion
def fat(n, acc=1):
if n <= 1:
return acc
else:
return fat(n - 1, acc * n)
print fat(1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment