Last active
August 11, 2017 08:40
-
-
Save linkin-park/4998b231390028611fe2924cd85af07b to your computer and use it in GitHub Desktop.
Erlang Class - 2nd Recursion - Assignment
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
%tail Recursion | |
-module(recursion_1_3_4). | |
-export([sum/1,fib/1,perfect/1,perfect1/1]). | |
% Try 1 | |
% | |
% Sum of numbers | |
% F(0)+F(1)+....F(N-1)+F(N) | |
sum(N) -> sum(N-1,N). | |
sum(0,K)->K; | |
sum(N,K)->sum(N-1,K+N). | |
% Try 2 | |
% | |
% max of numbers | |
% F(0)+F(1)+....F(N-1)+F(N) | |
%fibonnaci | |
%0,1,2,3,4,5... | |
%0,1,1,2,3,5,... | |
fib(N)-> fib(N,0,1). | |
fib(N,N1,_) when N==0 -> N1; | |
fib(N,N1,N2) when N>0->fib(N-1,N2,N1+N2). | |
%fib(4) | |
%fib(4,0,1) | |
%fib(3,1,1) | |
%fib(2,1,2) | |
%fib(1,2,3) | |
%fib(0,3,5) | |
%3 | |
%Perfect numbers | |
%A positive integer is perfect when it is the sum of its divisors, e.g. 6=1+2+3, 28=1+2+4+7+14. | |
%Define a function perfect/1 that takes a positive number N and returns a boolean which indicates whether or not the number is perfect. You may well want to %use an accumulating parameter to hold the sum of the divisors “so far”. | |
perfect(N)->divisor(N,1,0). | |
divisor(N,Num,Sum) when Num == N -> Sum == N; | |
divisor(N,Num,Sum) -> | |
if (N>0) and (N rem Num == 0) -> divisor(N,Num+1,Sum+Num); | |
true -> divisor(N,Num+1,Sum) | |
end. | |
perfect1(N)->divisor1(N,1,0). | |
divisor1(N,Num,Sum) when Num == N -> Sum == N; | |
divisor1(N,Num,Sum) when(N>0) and (N rem Num == 0) -> divisor1(N,Num+1,Sum+Num); | |
divisor1(N,Num,Sum) when(N>0) -> divisor1(N,Num+1,Sum). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment