Skip to content

Instantly share code, notes, and snippets.

@fastzen
Created February 28, 2017 18:46
Show Gist options
  • Save fastzen/c016a1bc27d9d6e50036e201eef0f035 to your computer and use it in GitHub Desktop.
Save fastzen/c016a1bc27d9d6e50036e201eef0f035 to your computer and use it in GitHub Desktop.
tailrecursion.erl
-module(tailrecursion).
-export([fac/1,loop/1,sum/1,maximum/1,fib/1,perfect/1]).
fac(N) -> fac(N,1).
fac(0,P) ->
P;
fac(N,P) when N>0 ->
fac(N-1,P*N).
loop(N) when N>0 ->
io:format("~p~n",[N]),
loop(N-1);
loop(_) ->
io:format("bye~n").
sum(N) -> sum(N,0).
sum(0,P) -> P;
sum(N,P) when N>0 ->
sum(N-1,N+P).
maximum(N) -> maximum(N,0).
maximum(0,P) -> P;
maximum(N,P) when N>0 ->
case N>P of
true -> maximum(N-1,N);
false -> maximum(N-1,P)
end.
fib(N) ->
fib(N,0,1).
fib(0,P,_C) ->
P;
fib(N,P,C) ->
fib(N-1,C,P+C).
perfect(N) ->
perfect(N,1,0).
perfect(N,N,S) ->
N==S;
perfect(N,M,S) when N rem M == 0 ->
perfect(N,M+1,S+M);
perfect(N,M,S) ->
perfect(N,M+1,S).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment