Last active
December 15, 2022 06:33
-
-
Save shun159/a1ca60eed99f377fc72a38be57f9f2d8 to your computer and use it in GitHub Desktop.
Comparision of Program for Fibonacci numbers. Implement using Dynamic Programming and Conventional Implementation.
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
% | |
% timer:tc(fun() -> fib:fib(41) end). | |
% {1398640,165580141} | |
% | |
% timer:tc(fun() -> fib:fib_dp1(41) end). | |
% {84,165580141} | |
% | |
% timer:tc(fun() -> fib:fib_dp2(41) end). | |
% {5,165580141} | |
% | |
-module(fib). | |
-export([fib/1, fib_dp1/1, fib_dp2/1]). | |
fib(X) when X < 2 -> X; | |
fib(X) -> fib(X - 1) + fib(X - 2). | |
fib_dp1(N, X, Memo) when N =< X -> | |
Memo1 = Memo#{N := maps:get(N - 1, Memo) + maps:get(N - 2, Memo)}, | |
fib_dp(N + 1, X, Memo1); | |
fib_dp1(_, _, Memo) -> | |
Memo. | |
fib_dp1(X) -> | |
FoldFun = fun(N, Acc) -> maps:put(N, 0, Acc) end, | |
Memo0 = lists:foldr(FoldFun, #{}, lists:seq(0, X)), | |
Memo1 = fib_dp1(2, X, Memo0#{0 := 0, 1 := 1}), | |
maps:get(X, Memo1). | |
fib_dp2(N) -> | |
fib_dp(N, 0, 1). | |
fib_dp2(0, Acc1, _) -> Acc1; | |
fib_dp2(C, Acc1, Acc2) -> | |
fib_dp2(C-1, Acc1+Acc2, Acc1). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment