Skip to content

Instantly share code, notes, and snippets.

@7-fl
Last active February 26, 2017 09:29
Show Gist options
  • Save 7-fl/f6a083c274f8bdc777139e6511b7cde9 to your computer and use it in GitHub Desktop.
Save 7-fl/f6a083c274f8bdc777139e6511b7cde9 to your computer and use it in GitHub Desktop.
perf_tests() ->
true = perf(6),
true = perf(28),
false = perf(7),
false = perf(15),
false = perf(0),
all_tests_passed.
perf(0) -> false;
perf(N) ->
Divisor = 1,
DivSum = 0,
perf(N, Divisor, DivSum).
perf(N, N, DivSum) ->
DivSum =:= N;
perf(N, Divisor, DivSum) when (N rem Divisor =:= 0) ->
perf(N, Divisor+1, DivSum+Divisor);
perf(N, Divisor, DivSum) ->
perf(N, Divisor+1, DivSum).
%---stop checking divisors when you reach N/2:
perf(0) -> false;
perf(N) ->
Divisor = 1,
DivSum = 0,
MaxDivisor = (N div 2) + 1,
perf(N, MaxDivisor, Divisor, DivSum).
perf(N, MaxDivisor, MaxDivisor, DivSum) ->
DivSum =:= N;
perf(N, MaxDivisor, Divisor, DivSum) when (N rem Divisor =:= 0) ->
perf(N, MaxDivisor, Divisor+1, DivSum+Divisor);
perf(N, MaxDivisor, Divisor, DivSum) ->
perf(N, MaxDivisor, Divisor+1, DivSum).
%-----------------
fib_tests() ->
0 = fib(0),
1 = fib(1),
1 = fib(2),
2 = fib(3),
3 = fib(4),
5 = fib(5),
all_tests_passed.
fib(0) -> 0;
fib(1) -> 1;
fib(N) ->
N1 = 1, % N1 => N-1
N2 = 0, % N2 => N-2
fib_acc(N, N1, N2).
fib_acc(2, N1, N2) ->
N1 + N2;
fib_acc(N, N1, N2) ->
fib_acc(N-1, N1+N2, N1).
%-----------------
fmax_tests() ->
10 = fmax(fun(X) -> X*2 end, 5),
2 = fmax(fun(X) -> X+2 end, 0),
all_tests_passed.
fmax(Func, N) ->
Max = 0,
fmax(Func, N, Max).
fmax(Func, 0, Max) ->
max(Func(0), Max);
fmax(Func, N, Max) ->
fmax(Func, N-1, max(Func(N), Max) ).
%------------------
fsum_tests() ->
12 = fsum(fun(X) -> X*2 end, 3),
14 = fsum(fun(X) -> X+2 end, 3),
all_tests_passed.
fsum(Func, N) ->
Acc = 0,
fsum(Func, N, Acc).
fsum(Func, 0, Acc) ->
Acc + Func(0);
fsum(Func, N, Acc) ->
fsum(Func, N-1, Acc + Func(N) ).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment