Skip to content

Instantly share code, notes, and snippets.

@apbarrero
Last active June 24, 2017 13:52
Show Gist options
  • Save apbarrero/8304623d6106e685ef1da87dc25d71e2 to your computer and use it in GitHub Desktop.
Save apbarrero/8304623d6106e685ef1da87dc25d71e2 to your computer and use it in GitHub Desktop.
Tail recursion exercise
-module(tailrecurs).
-export([fib/1, perfect/1, testPerfect/0]).
fib(0) -> 0;
fib(1) -> 1;
fib(N) when N>1 ->
fib(N, 1, 0).
fib(2, Acc1, Acc2) -> Acc1 + Acc2;
fib(N, Acc1, Acc2) when N>2 -> fib(N-1, Acc1 + Acc2, Acc1).
% fib(4)
% fib(4, 1, 0)
% fib(3, 1, 1)
% fib(2, 2, 1)
% 2 + 1 = 3
perfect(1) -> true;
perfect(N) -> perfect(N-1, N, 0).
perfect(0, N, S) -> N==S;
perfect(M, N, S) when N rem M == 0 -> perfect(M-1, N, S + M);
perfect(M, N, S) when N rem M =/= 0 -> perfect(M-1, N, S).
testPerfect() ->
perfect(1) and perfect(6) and perfect(28) and not perfect(16).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment