LoginSignup
2
2

More than 5 years have passed since last update.

Recusive and Tail Recursive: factorial

Last updated at Posted at 2016-01-08

Recursive

# Definiation of factorial
# 0! = 1
# n! = n * (n - 1)!
#
#|Call:1    │->│Call:2    │->│Call:3    │->│Call:4    │->│Call:5    │
#│n:4       │  │n:3       │  │n:2       │  │n:1       │  │n:0       │
#│value : 24│<-│value : 6 │<-│value : 2 │<-│value : 1 │<-│value : 1 │
#
#@profile
def fact(n):
    if n == 0: return 1
    return n * fact(n - 1)

fact(20)

Tail Recursive

# e.g
#fact(4, 1)
#  fact(3, 4)
#    fact(2, 12)
#      fact(1, 24)
#        fact(0, 24)
#        => return x: 24
#      => 24
#    => 24
#  => 24
#=> 24
#@profile
def fact(n, x=1):
    if n == 0: return x
    return fact(n - 1, n * x)

print(fact(4))

# it can be rewritten like this
# tail recursive optimization
def opt_fact(n):
    x = 1
    while n > 0:
        x *= n
        n -= 1
    return x

print(opt_fact(4))

再帰定義のなかで、最後に再帰呼び出しを行う場合を「末尾再帰 (tail recursion) 」といいます。

ref:
http://www.geocities.jp/m_hiroi/light/python03.html

tail recursive
http://melborne.github.io/2009/03/18/notitle/

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2