Skip to content

Instantly share code, notes, and snippets.

@fpdevil
Last active February 24, 2017 07:00
Show Gist options
  • Save fpdevil/63425bd4582b658b6500b73744af5839 to your computer and use it in GitHub Desktop.
Save fpdevil/63425bd4582b658b6500b73744af5839 to your computer and use it in GitHub Desktop.
%%%-----------------------------------------------------------------------------
%%% @author Sampath Singamsetty <>
%%% @copyright (C) 2017, Sampath Singamsetty
%%% @doc Week1 exercises
%%% www.futurelearn.com/courses/functional-programming-erlang
%%% @end
%%% Created : 23 Feb 2017 by Sampath Singamsetty <>
%%%-----------------------------------------------------------------------------
-module(week1).
-export([fib/1, pieces/1]).
-export([fibonacci/1, perfect/1]).
%% fibonacci numbers
%% helper functions for fast Fibonacci
fibStep({X, Y}) ->
{Y, X + Y}.
fibPair(0) ->
{0, 1};
fibPair(N) when N > 0 ->
fibStep(fibPair(N-1)).
%% get first value of a pair
getFirst({X, _}) ->
X.
%% actual Fibonacci number
fib(0) ->
0;
fib(N) when N > 0 ->
getFirst(fibPair(N)).
%% tail recursive Fibonacci
fibonacci(N) ->
tail_fib(N, 0, 0, 0).
tail_fib(Acc, Acc, X, Y) -> X + Y;
tail_fib(Acc, 0, _, _) -> tail_fib(Acc, 1, 0, 0);
tail_fib(Acc, 1, _, _) -> tail_fib(Acc, 2, 1, 0);
tail_fib(Acc, N, X, Y) -> tail_fib(Acc, N+1, Y + X, X).
%% N cuts problem
%% given N lines, return the number of parts plane is divided into.
%% lines pieces
%% f(0) 1
%% f(1) 2
%% f(2) 4
%% .. ..
%% f(n-2) (n-2) + f(n-3)
%% f(n-1) (n-1) + f(n-2)
%% f(n) n + f(n-1)
%% ---------------------------
%% add on both left and right side, cancel common terms
%% This gives the below general formula
%% f(n) = SUM (n) + 1
%% f(n) = (2 + n*n + n)/2
%%
pieces(0) ->
1;
pieces(N) when N > 0 ->
(2 + N*N + N) div 2.
%% perfect numbers
perfect(N) ->
L = lists:filter(fun(X) -> N rem X =:= 0 end, lists:seq(1, N-1)),
lists:sum(L) =:= N.
% 27> week1:perfect(6).
% true
% 28> week1:perfect(8).
% false
% 29> week1:perfect(28).
% true
% 30> week1:perfect(24).
% false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment