Created
February 28, 2017 18:39
-
-
Save fastzen/aad797d7129862da7769f32595e07501 to your computer and use it in GitHub Desktop.
tailrecursion.erl
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
-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(0) -> 0; | |
fib(1) -> 1; | |
fib(N) -> fib(N,1,0). | |
fib(1,P1,P2) -> | |
P1+P2; | |
fib(N,P1,P2) when N>0 -> | |
fib(N-1,P1+P2,P1). | |
perfect(N) -> perfect(N,N div 2,0). | |
perfect(N,0,N) -> true; | |
perfect(_,0,_) -> false; | |
perfect(N,P,A) when N rem P == 0 -> perfect(N,P-1,A+P); | |
perfect(N,P,A) -> perfect(N,P-1,A). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment