-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtailRecursion.rb
More file actions
29 lines (26 loc) · 764 Bytes
/
tailRecursion.rb
File metadata and controls
29 lines (26 loc) · 764 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#-----------------------------------------------------#
# Tail recursion is the quickest way to get the output#
#----------------------------------------------------------------
# Comparison of tail and non-tail recursion
# Tail Recursion :
# There is no other operations is performed after recursion
# Non-tail Recursion :
# Opposite to Tail recursion
#----------------------------------------------------------------
require "benchmark"
#-------------------
# Non-Tail Recursion
def fact(n)
return 1 if(n == 0)
return n * fact(n - 1)
end
#---------------
# Tail Recursion
def fact_tail(n, k)
return k if(n == 0)
return fact_tail(n-1, k*n)
end
Benchmark.bm do |x|
x.report("Non-tail:") { p fact(100)}
x.report("Tail:") { p fact_tail(100, 1)}
end