wip1 fib done

This commit is contained in:
Ivan I. Ovchinnikov 2023-02-10 13:21:56 +03:00
parent 396650eec0
commit 536dbf6f15
2 changed files with 37 additions and 3 deletions

View File

@ -1,5 +1,5 @@
-module(fib).
-export([fib_p/1]).
-export([fib_p/1, fib_g/1, tail_fib/1, say/0, start_time_check/0]).
% Сопоставление с образцом
fib_p(0) -> 0;
@ -10,3 +10,23 @@ fib_p(N) -> fib_p(N - 1) + fib_p(N - 2).
fib_g(N) when N < 1 -> 0;
fib_g(N) when N < 2 -> 1;
fib_g(N) -> fib_g(N - 1) + fib_g(N - 2).
% Хвостовая рекурсия
tail_fib(N) -> tfib(N, 0, 1).
tfib(0, Result, Next) -> Result;
tfib(N, Result, Next) -> tfib(N - 1, Next, Result + Next).
say() -> io:format("The result is: ~p~n", [tail_fib(10)]).
exec_time(Depth) ->
Start = os:timestamp(),
fib_p(Depth),
io:format("Depth = ~p, Time ~f sec~n", [Depth, (timer:now_diff(os:timestamp(), Start) / 1000)]).
for(0, _, _) -> [];
for(N, Term, Step) when N > 0 ->
exec_time(N),
[Term | for(N - Step, Term, Step)].
start_time_check() ->
for(40, 20, 5).

View File

@ -11,7 +11,8 @@
fib_test_() -> [
{"Test fib_p", fun test_fib_p/0 },
{"Test fib_g", fun test_fib_g/0 }
{"Test fib_g", fun test_fib_g/0 },
{"Test tail_fib", fun test_tail_fib/0 }
].
test_fib_p() ->
@ -39,3 +40,16 @@ test_fib_g() ->
?assertEqual(21, fib:fib_g(8)),
?assertEqual(34, fib:fib_g(9)),
?assertEqual(55, fib:fib_g(10)).
test_tail_fib() ->
?assertEqual(0, fib:tail_fib(0)),
?assertEqual(1, fib:tail_fib(1)),
?assertEqual(1, fib:tail_fib(2)),
?assertEqual(2, fib:tail_fib(3)),
?assertEqual(3, fib:tail_fib(4)),
?assertEqual(5, fib:tail_fib(5)),
?assertEqual(8, fib:tail_fib(6)),
?assertEqual(13, fib:tail_fib(7)),
?assertEqual(21, fib:tail_fib(8)),
?assertEqual(34, fib:tail_fib(9)),
?assertEqual(55, fib:tail_fib(10)).