Last active
April 25, 2019 10:09
-
-
Save KevinSia/f69886e372fc71862b586b0eda8242f7 to your computer and use it in GitHub Desktop.
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
# Implement an iterative version of the factorial function | |
def factorial_iterative(n) | |
return n if n <= 1 | |
total = 1 | |
n.downto(1) { |i| total *= i } | |
return total | |
end | |
# def factorial_iterative(n) | |
# return n if n <= 1 | |
# total = 1 | |
# 1.upto(5) { |i| total *= i } | |
# return total | |
# end | |
# def factorial_iterative(n) | |
# return n if n <= 1 | |
# (1..n).reduce(:*) | |
# end | |
# def factorial_iterative(n) | |
# return n if n <= 1 | |
# (1..n).reduce { |total, num| total *= num } | |
# # with a custom starting number | |
# (1..n).reduce(1) { |total, num| total *= num } | |
# end | |
# Implement a recursive version of the factorial function | |
def factorial_recursive(n) | |
if n <= 1 | |
return n | |
else | |
n * factorial_recursive(n - 1) | |
end | |
end | |
# Tail call optimization speeds up recursive computations | |
# by making the return value of the function to either by a single value or the function call itself. | |
# in the above example the return value is `n * factorial_recursive(n - 1)` | |
# which the ruby program will make a new stack for the function call for the multiplication to complete | |
# However, tail call optimization is not enabled by default in Ruby. | |
def factorial_recursive_tail_call(n, r = 1) | |
if n < 2 | |
n | |
else | |
# f(counter, accumulator) | |
# f(5) | |
# f(4, 5 * 1) | |
# f(3, 4 * 5) | |
# f(2, 3 * 20) | |
# f(1, 2 * 60) | |
f(n - 1, n * r) | |
end | |
end | |
puts factorial_iterative(10) == 362880 | |
puts factorial_recursive(10) == 362880 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment