Download code
From LiteratePrograms
Back to Fibonacci_numbers_(Erlang)
Download for Windows: single file, zip
Download for UNIX: single file, zip, tar.gz, tar.bz2
fib.erl
1 % Copyright (c) 2008 the authors listed at the following URL, and/or 2 % the authors of referenced articles or incorporated external code: 3 % http://en.literateprograms.org/Fibonacci_numbers_(Erlang)?action=history&offset=20070611025851 4 % 5 % Permission is hereby granted, free of charge, to any person obtaining 6 % a copy of this software and associated documentation files (the 7 % "Software"), to deal in the Software without restriction, including 8 % without limitation the rights to use, copy, modify, merge, publish, 9 % distribute, sublicense, and/or sell copies of the Software, and to 10 % permit persons to whom the Software is furnished to do so, subject to 11 % the following conditions: 12 % 13 % The above copyright notice and this permission notice shall be 14 % included in all copies or substantial portions of the Software. 15 % 16 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 % EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 % IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 % CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 21 % TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 22 % SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 % 24 % Retrieved from: http://en.literateprograms.org/Fibonacci_numbers_(Erlang)?oldid=10477 25 26 27 -module(fib). 28 -export([fibo/1, fibo2/1, fibo3/1, print_nfibos/2]). 29 30 %% print fibo arg. and result, with function as parameter 31 32 print_nfibos( N, FiboFunc) -> printfibos( N, FiboFunc, 0). 33 34 printfibos( 0, FiboFunc, N) -> %% last recursion 35 Res = FiboFunc(N), 36 io:fwrite("~w ~w~n", [N, Res]) ; 37 38 printfibos( Iter, FiboFunc, N) when Iter > 0 -> 39 Res = FiboFunc(N), 40 io:fwrite("~w ~w~n", [N, Res]), 41 printfibos( Iter -1, FiboFunc, N +1). 42 43 44 fibo(0) -> 0 ; 45 fibo(1) -> 1 ; 46 fibo(N) when N > 0 -> fibo(N-1) + fibo(N-2) . 47 48 49 50 fibo2_tr( 0, Result, _Next) -> Result ; %% last recursion output 51 52 fibo2_tr( Iter, Result, Next) when Iter > 0 -> fibo2_tr( Iter -1, Next, Result + Next) . 53 54 fibo2( N) -> fibo2_tr( N, 0, 1) . 55 56 fibo3(N) -> 57 {Fib, _} = fibo3(N, {1, 1}, {0, 1}), 58 Fib. 59 60 fibo3(0, _, Pair) -> Pair; 61 fibo3(N, {Fib1, Fib2}, Pair) when N rem 2 == 0 -> 62 SquareFib1 = Fib1*Fib1, 63 fibo3(N div 2, {2*Fib1*Fib2 - SquareFib1, SquareFib1 + Fib2*Fib2}, Pair); 64 fibo3(N, {FibA1, FibA2}=Pair, {FibB1, FibB2}) -> 65 fibo3(N-1, Pair, {FibA1*FibB2 + FibB1*(FibA2 - FibA1), FibA1*FibB1 + FibA2*FibB2}). 66 67 68
