Last active
February 25, 2017 21:27
-
-
Save javajosh/28a56be862d9f31febabadaa9333bf04 to your computer and use it in GitHub Desktop.
Excercises for https://www.futurelearn.com/courses/functional-programming-erlang/1/steps/151655#fl-comments
This file contains hidden or 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
%%%------------------------------------------------------------------- | |
%%% @author josh | |
%%% Created : 25. Feb 2017 10:44 AM | |
%%%------------------------------------------------------------------- | |
-module(tail). | |
-author("josh"). | |
-export([fib/3, fib/1, loop/1, perfect/1, lp/1]). | |
%Hmm..there seems to be a bug in this one. | |
fib(N) -> fib(N,0,1). | |
fib(0,N1,N2) -> N1 + N2; | |
fib(N, N1, N2) when N>0 -> | |
fib(N-1, N2, N1 + N2). | |
loop(N) when N>0 -> | |
io:format("~p~n", [N]), | |
loop(N-1); | |
loop(0) -> | |
io:format("bye~n"). | |
% Test cases: 6, 28, 496, 8128, and 33550336 | |
perfect(N) -> | |
N == perfect(N,1,0). | |
perfect(N,D,ACC) when D>N/2 -> | |
ACC; | |
perfect(N,D,ACC) when (N rem D) == 0 -> | |
perfect(N, D+1, ACC + D); | |
perfect(N,D,ACC) -> | |
perfect(N, D+1, ACC). | |
%BONUS: find perfect numbers in the first N integers | |
io(N, X) when X ->io:format("Perfect: ~p~n",[N]); | |
io(_,_) -> false. | |
lp(N) -> lp(N,perfect(N)). | |
lp(N, X) when N>0 -> | |
io(N,X), | |
lp(N-1, perfect(N-1)); | |
lp(0,_) -> | |
io:format("bye~n"). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment