This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1,2 @@
%<:0D:>~$<:01:~%>=<:a94fad42221f2702:>~>
}:_s:{x{={~$x+%{=>~>x~-x<:0D:~>~>~^:_s:?

View file

@ -0,0 +1,23 @@
The '''Fibonacci sequence''' is a sequence F<sub>n</sub> of natural numbers defined recursively:
F<sub>0</sub> = 0
F<sub>1</sub> = 1
F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub>, if n>1
Write a function to generate the nth Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
F<sub>n</sub> = F<sub>n+2</sub> - F<sub>n+1</sub>, if n<0
Support for negative n in the solution is optional.
;Cf.:
* [[Fibonacci n-step number sequences]]
;References:
* [[wp:Fibonacci number|Wikipedia, Fibonacci number]]
* [[wp:Lucas number|Wikipedia, Lucas number]]
* [http://mathworld.wolfram.com/FibonacciNumber.html MathWorld, Fibonacci Number]
* [http://www.math-cs.ucmo.edu/~curtisc/articles/howardcooper/genfib4.pdf Some identities for r-Fibonacci numbers]
*[[oeis:A000045|OEIS Fibonacci numbers]]
*[[oeis:A000032|OEIS Lucas numbers]]

View file

@ -0,0 +1,6 @@
---
category:
- Recursion
- Memoization
- Classic CS problems and programs
note: Arithmetic operations

View file

@ -0,0 +1,17 @@
(defun fast-fib-r (n a b)
(if (or (zp n) (zp (1- n)))
b
(fast-fib-r (1- n) b (+ a b))))
(defun fast-fib (n)
(fast-fib-r n 1 1))
(defun first-fibs-r (n i)
(declare (xargs :measure (nfix (- n i))))
(if (zp (- n i))
nil
(cons (fast-fib i)
(first-fibs-r n (1+ i)))))
(defun first-fibs (n)
(first-fibs-r n 0))

View file

@ -0,0 +1,13 @@
PROC analytic fibonacci = (LONG INT n)LONG INT:(
LONG REAL sqrt 5 = long sqrt(5);
LONG REAL p = (1 + sqrt 5) / 2;
LONG REAL q = 1/p;
ROUND( (p**n + q**n) / sqrt 5 )
);
FOR i FROM 1 TO 30 WHILE
print(whole(analytic fibonacci(i),0));
# WHILE # i /= 30 DO
print(", ")
OD;
print(new line)

View file

@ -0,0 +1,17 @@
PROC iterative fibonacci = (INT n)INT:
CASE n+1 IN
0, 1, 1, 2, 3, 5
OUT
INT even:=3, odd:=5;
FOR i FROM odd+1 TO n DO
(ODD i|odd|even) := odd + even
OD;
(ODD n|odd|even)
ESAC;
FOR i FROM 0 TO 30 WHILE
print(whole(iterative fibonacci(i),0));
# WHILE # i /= 30 DO
print(", ")
OD;
print(new line)

View file

@ -0,0 +1,2 @@
PROC recursive fibonacci = (INT n)INT:
( n < 2 | n | fib(n-1) + fib(n-2));

View file

@ -0,0 +1,18 @@
MODE YIELDINT = PROC(INT)VOID;
PROC gen fibonacci = (INT n, YIELDINT yield)VOID: (
INT even:=0, odd:=1;
yield(even);
yield(odd);
FOR i FROM odd+1 TO n DO
yield( (ODD i|odd|even) := odd + even )
OD
);
main:(
# FOR INT n IN # gen fibonacci(30, # ) DO ( #
## (INT n)VOID:(
print((" ",whole(n,0)))
# OD # ));
print(new line)
)

View file

@ -0,0 +1,30 @@
[]INT const fibonacci = []INT( -1836311903, 1134903170,
-701408733, 433494437, -267914296, 165580141, -102334155,
63245986, -39088169, 24157817, -14930352, 9227465, -5702887,
3524578, -2178309, 1346269, -832040, 514229, -317811, 196418,
-121393, 75025, -46368, 28657, -17711, 10946, -6765, 4181,
-2584, 1597, -987, 610, -377, 233, -144, 89, -55, 34, -21, 13,
-8, 5, -3, 2, -1, 1, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711,
28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040,
1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817,
39088169, 63245986, 102334155, 165580141, 267914296, 433494437,
701408733, 1134903170, 1836311903
)[@-46];
PROC VOID value error := stop;
PROC lookup fibonacci = (INT i)INT: (
IF LWB const fibonacci <= i AND i<= UPB const fibonacci THEN
const fibonacci[i]
ELSE
value error; SKIP
FI
);
FOR i FROM 0 TO 30 WHILE
print(whole(lookup fibonacci(i),0));
# WHILE # i /= 30 DO
print(", ")
OD;
print(new line)

View file

@ -0,0 +1,3 @@
$ awk 'func fib(n){return(n<2?n:fib(n-1)+fib(n-2))}{print "fib("$1")="fib($1)}'
10
fib(10)=55

View file

@ -0,0 +1,7 @@
public function fib(n:uint):uint
{
if (n < 2)
return n;
return fib(n - 1) + fib(n - 2);
}

View file

@ -0,0 +1,19 @@
with Ada.Text_IO, Ada.Command_Line;
procedure Fib is
X: Positive := Positive'Value(Ada.Command_Line.Argument(1));
function Fib(P: Positive) return Positive is
begin
if P <= 2 then
return 1;
else
return Fib(P-1) + Fib(P-2);
end if;
end Fib;
begin
Ada.Text_IO.Put("Fibonacci(" & Integer'Image(X) & " ) = ");
Ada.Text_IO.Put_Line(Integer'Image(Fib(X)));
end Fib;

View file

@ -0,0 +1,20 @@
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Fibonacci is
function Fibonacci (N : Natural) return Natural is
This : Natural := 0;
That : Natural := 1;
Sum : Natural;
begin
for I in 1..N loop
Sum := This + That;
That := This;
This := Sum;
end loop;
return This;
end Fibonacci;
begin
for N in 0..10 loop
Put_Line (Positive'Image (Fibonacci (N)));
end loop;
end Test_Fibonacci;

View file

@ -0,0 +1,33 @@
with Ada.Text_IO, Ada.Command_Line, Crypto.Types.Big_Numbers;
procedure Fibonacci is
X: Positive := Positive'Value(Ada.Command_Line.Argument(1));
Bit_Length: Positive := 1 + (696 * X) / 1000;
-- that number of bits is sufficient to store the full result.
package LN is new Crypto.Types.Big_Numbers
(Bit_Length + (32 - Bit_Length mod 32));
-- the actual number of bits has to be a multiple of 32
use LN;
function Fib(P: Positive) return Big_Unsigned is
Previous: Big_Unsigned := Big_Unsigned_Zero;
Result: Big_Unsigned := Big_Unsigned_One;
Tmp: Big_Unsigned;
begin
-- Result = 1 = Fibonacci(1)
for I in 1 .. P-1 loop
Tmp := Result;
Result := Previous + Result;
Previous := Tmp;
-- Result = Fibonacci(I+1))
end loop;
return Result;
end Fib;
begin
Ada.Text_IO.Put("Fibonacci(" & Integer'Image(X) & " ) = ");
Ada.Text_IO.Put_Line(LN.Utils.To_String(Fib(X)));
end Fibonacci;

View file

@ -0,0 +1,6 @@
def fib(n as Int) as Int
if n < 2
return 1
end
return fib(n-1) + fib(n-2)
end

View file

@ -0,0 +1,11 @@
set fibs to {}
set x to (text returned of (display dialog "What fibbonaci number do you want?" default answer "3"))
set x to x as integer
repeat with y from 1 to x
if (y = 1 or y = 2) then
copy 1 to the end of fibs
else
copy ((item (y - 1) of fibs) + (item (y - 2) of fibs)) to the end of fibs
end if
end repeat
return item x of fibs

View file

@ -0,0 +1,18 @@
Loop, 5
MsgBox % fib(A_Index)
Return
fib(n)
{
If (n < 2)
Return n
i := last := this := 1
While (i <= n)
{
new := last + this
last := this
this := new
i++
}
Return this
}

View file

@ -0,0 +1,17 @@
/*
Important note: the recursive version would be very slow
without a global or static array. The iterative version
handles also negative arguments properly.
*/
FibR(n) { ; n-th Fibonacci number (n>=0, recursive with static array Fibo)
Static
Return n<2 ? n : Fibo%n% ? Fibo%n% : Fibo%n% := FibR(n-1)+FibR(n-2)
}
Fib(n) { ; n-th Fibonacci number (n < 0 OK, iterative)
a := 0, b := 1
Loop % abs(n)-1
c := b, b += a, a := c
Return n=0 ? 0 : n>0 || n&1 ? b : -b
}

View file

@ -0,0 +1,27 @@
#AutoIt Version: 3.2.10.0
$n0 = 0
$n1 = 1
$n = 10
MsgBox (0,"Iterative Fibonacci ", it_febo($n0,$n1,$n))
Func it_febo($n_0,$n_1,$N)
$first = $n_0
$second = $n_1
$next = $first + $second
$febo = 0
For $i = 1 To $N-3
$first = $second
$second = $next
$next = $first + $second
Next
if $n==0 Then
$febo = 0
ElseIf $n==1 Then
$febo = $n_0
ElseIf $n==2 Then
$febo = $n_1
Else
$febo = $next
EndIf
Return $febo
EndFunc

View file

@ -0,0 +1,19 @@
#AutoIt Version: 3.2.10.0
$n0 = 0
$n1 = 1
$n = 10
MsgBox (0,"Recursive Fibonacci ", rec_febo($n0,$n1,$n))
Func rec_febo($r_0,$r_1,$R)
if $R<3 Then
if $R==2 Then
Return $r_1
ElseIf $R==1 Then
Return $r_0
ElseIf $R==0 Then
Return 0
EndIf
Return $R
Else
Return rec_febo($r_0,$r_1,$R-1) + rec_febo($r_0,$r_1,$R-2)
EndIf
EndFunc

View file

@ -0,0 +1,14 @@
FUNCTION itFib (n)
n1 = 0
n2 = 1
FOR k = 1 TO ABS(n)
sum = n1 + n2
n1 = n2
n2 = sum
NEXT k
IF n < 0 THEN
itFib = n1 * ((-1) ^ ((-n) + 1))
ELSE
itFib = n1
END IF
END FUNCTION

View file

@ -0,0 +1,38 @@
DECLARE FUNCTION fibonacci& (n AS INTEGER)
REDIM SHARED fibNum(1) AS LONG
fibNum(1) = 1
'*****sample inputs*****
PRINT fibonacci(0) 'no calculation needed
PRINT fibonacci(13) 'figure F(2)..F(13)
PRINT fibonacci(-42) 'figure F(14)..F(42)
PRINT fibonacci(47) 'error: too big
'*****sample inputs*****
FUNCTION fibonacci& (n AS INTEGER)
DIM a AS INTEGER
a = ABS(n)
SELECT CASE a
CASE 0 TO 46
SHARED fibNum() AS LONG
DIM u AS INTEGER, L0 AS INTEGER
u = UBOUND(fibNum)
IF a > u THEN
REDIM PRESERVE fibNum(a) AS LONG
FOR L0 = u + 1 TO a
fibNum(L0) = fibNum(L0 - 1) + fibNum(L0 - 2)
NEXT
END IF
IF n < 0 THEN
fibonacci = fibNum(a) * ((-1) ^ (a + 1))
ELSE
fibonacci = fibNum(n)
END IF
CASE ELSE
'limited to signed 32-bit int (LONG)
'F(47)=&hB11924E1
ERROR 6 'overflow
END SELECT
END FUNCTION

View file

@ -0,0 +1,7 @@
FUNCTION recFib (n)
IF (n < 2) THEN
recFib = n
ELSE
recFib = recFib(n - 1) + recFib(n - 2)
END IF
END FUNCTION

View file

@ -0,0 +1,21 @@
DATA -1836311903,1134903170,-701408733,433494437,-267914296,165580141,-102334155
DATA 63245986,-39088169,24157817,-14930352,9227465,-5702887,3524578,-2178309
DATA 1346269,-832040,514229,-317811,196418,-121393,75025,-46368,28657,-17711
DATA 10946,-6765,4181,-2584,1597,-987,610,-377,233,-144,89,-55,34,-21,13,-8,5,-3
DATA 2,-1,1,0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765
DATA 10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269
DATA 2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986
DATA 102334155,165580141,267914296,433494437,701408733,1134903170,1836311903
DIM fibNum(-46 TO 46) AS LONG
FOR n = -46 TO 46
READ fibNum(n)
NEXT
'*****sample inputs*****
FOR n = -46 TO 46
PRINT fibNum(n),
NEXT
PRINT
'*****sample inputs*****

View file

@ -0,0 +1,19 @@
PRINT FNfibonacci_r(1), FNfibonacci_i(1)
PRINT FNfibonacci_r(13), FNfibonacci_i(13)
PRINT FNfibonacci_r(26), FNfibonacci_i(26)
END
DEF FNfibonacci_r(N)
IF N < 2 THEN = N
= FNfibonacci_r(N-1) + FNfibonacci_r(N-2)
DEF FNfibonacci_i(N)
LOCAL F, I, P, T
IF N < 2 THEN = N
P = 1
FOR I = 1 TO N
T = F
F += P
P = T
NEXT
= F

View file

@ -0,0 +1,17 @@
main:
{ argv 0 th $d
fib
%d cr << }
fib!:
{ dup zero?
{ dup one?
{ cp <- 2 - fib -> 1 - fib + }
{ zap 1 }
if }
{ zap 1 }
if }
zero?!: { 0 = }
one?!: { 1 = }

View file

@ -0,0 +1,21 @@
::fibo.cmd
@echo off
if "%1" equ "" goto :eof
call :fib %1
echo %errorlevel%
goto :eof
:fib
setlocal enabledelayedexpansion
if %1 geq 2 goto :ge2
exit /b %1
:ge2
set /a r1 = %1 - 1
set /a r2 = %1 - 2
call :fib !r1!
set r1=%errorlevel%
call :fib !r2!
set r2=%errorlevel%
set /a r0 = r1 + r2
exit /b !r0!

View file

@ -0,0 +1,2 @@
00:.1:.>:"@"8**++\1+:67+`#@_v
^ .:\/*8"@"\%*8"@":\ <

View file

@ -0,0 +1 @@
fib=.!arg:<2|fib$(!arg+-2)+fib$(!arg+-1)

View file

@ -0,0 +1,13 @@
(fib=
last i this new
. !arg:<2
| 0:?last:?i
& 1:?this
& whl
' ( !i+1:<!arg:?i
& !last+!this:?new
& !this:?last
& !new:?this
)
& !this
)

View file

@ -0,0 +1,2 @@
++++++++++
>>+<<[->[->+>+<<]>[-<+>]>[-<+>]<<<]

View file

@ -0,0 +1,37 @@
+++++ +++++ #0 set to n
>> + Init #2 to 1
<<
[
- #Decrement counter in #0
>>. Notice: This doesn't print it in ascii
To look at results you can pipe into a file and look with a hex editor
Copying sequence to save #2 in #4 using #5 as restore space
>>[-] Move to #4 and clear
>[-] Clear #5
<<< #2
[ Move loop
- >> + > + <<< Subtract #2 and add #4 and #5
]
>>>
[ Restore loop
- <<< + >>> Subtract from #5 and add to #2
]
<<<< Back to #1
Non destructive add sequence using #3 as restore value
[ Loop to add
- > + > + << Subtract #1 and add to value #2 and restore space #3
]
>>
[ Loop to restore #1 from #3
- << + >> Subtract from restore space #3 and add in #1
]
<< [-] Clear #1
>>>
[ Loop to move #4 to #1
- <<< + >>> Subtract from #4 and add to #1
]
<<<< Back to #0
]

View file

@ -0,0 +1,3 @@
fibonacci = { x |
true? x < 2, x, { fibonacci(x - 1) + fibonacci(x - 2) }
}

View file

@ -0,0 +1,9 @@
fib_aux = { x, next, result |
true? x == 0,
result,
{ fib_aux x - 1, next + result, next }
}
fibonacci = { x |
fib_aux x, 1, 0
}

View file

@ -0,0 +1,7 @@
cache = hash.new
fibonacci = { x |
true? cache.key?(x)
{ cache[x] }
{true? x < 2, x, { cache[x] = fibonacci(x - 1) + fibonacci(x - 2) }}
}

View file

@ -0,0 +1 @@
{0 1}{^^++[+[-^^-]\/}30.*\[e!vv

View file

@ -0,0 +1,16 @@
#include <iostream>
int main()
{
unsigned int a = 1, b = 1;
unsigned int target = 48;
for(unsigned int n = 3; n <= target; ++n)
{
unsigned int fib = a + b;
std::cout << "F("<< n << ") = " << fib << std::endl;
a = b;
b = fib;
}
return 0;
}

View file

@ -0,0 +1,21 @@
#include <iostream>
#include <gmpxx.h>
int main()
{
mpz_class a = mpz_class(1), b = mpz_class(1);
mpz_class target = mpz_class(100);
for(mpz_class n = mpz_class(3); n <= target; ++n)
{
mpz_class fib = b + a;
if ( fib < b )
{
std::cout << "Overflow at " << n << std::endl;
break;
}
std::cout << "F("<< n << ") = " << fib << std::endl;
a = b;
b = fib;
}
return 0;
}

View file

@ -0,0 +1,13 @@
#include <algorithm>
#include <vector>
#include <functional>
#include <iostream>
unsigned int fibonacci(unsigned int n) {
if (n == 0) return 0;
std::vector<int> v(n+1);
v[1] = 1;
transform(v.begin(), v.end()-2, v.begin()+1, v.begin()+2, std::plus<int>());
// "v" now contains the Fibonacci sequence from 0 up
return v[n];
}

View file

@ -0,0 +1,12 @@
#include <numeric>
#include <vector>
#include <functional>
#include <iostream>
unsigned int fibonacci(unsigned int n) {
if (n == 0) return 0;
std::vector<int> v(n, 1);
adjacent_difference(v.begin(), v.end()-1, v.begin()+1, std::plus<int>());
// "array" now contains the Fibonacci sequence from 1 up
return v[n-1];
}

View file

@ -0,0 +1,24 @@
#include <iostream>
template <int n> struct fibo
{
enum {value=fibo<n-1>::value+fibo<n-2>::value};
};
template <> struct fibo<0>
{
enum {value=0};
};
template <> struct fibo<1>
{
enum {value=1};
};
int main(int argc, char const *argv[])
{
std::cout<<fibo<12>::value<<std::endl;
std::cout<<fibo<46>::value<<std::endl;
return 0;
}

View file

@ -0,0 +1,35 @@
#include <iostream>
inline void fibmul(int* f, int* g)
{
int tmp = f[0]*g[0] + f[1]*g[1];
f[1] = f[0]*g[1] + f[1]*(g[0] + g[1]);
f[0] = tmp;
}
int fibonacci(int n)
{
int f[] = { 1, 0 };
int g[] = { 0, 1 };
while (n > 0)
{
if (n & 1) // n odd
{
fibmul(f, g);
--n;
}
else
{
fibmul(g, g);
n >>= 1;
}
}
return f[1];
}
int main()
{
for (int i = 0; i < 20; ++i)
std::cout << fibonacci(i) << " ";
std::cout << std::endl;
}

View file

@ -0,0 +1,15 @@
// Use Zeckendorf numbers to display Fibonacci sequence.
// Nigel Galloway October 23rd., 2012
int main(void) {
char NG[22] = {'1',0};
int x = -1;
N G;
for (int fibs = 1; fibs <= 20; fibs++) {
for (;G <= N(NG); ++G) x++;
NG[fibs] = '0';
NG[fibs+1] = 0;
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}

View file

@ -0,0 +1,11 @@
// Use Standard Template Library to display Fibonacci sequence.
// Nigel Galloway March 30th., 2013
#include <algorithm>
#include <iostream>
#include <iterator>
int main()
{
int x = 1, y = 1;
generate_n(std::ostream_iterator<int>(std::cout, " "), 21, [&]{int n=x; x=y; y+=n; return n;});
return 0;
}

View file

@ -0,0 +1,3 @@
long long unsigned fib(unsigned n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}

View file

@ -0,0 +1,10 @@
long long unsigned fib(unsigned n) {
long long unsigned last = 0, this = 1, new, i;
if (n < 2) return n;
for (i = 1 ; i < n ; ++i) {
new = last + this;
last = this;
this = new;
}
return this;
}

View file

@ -0,0 +1,6 @@
#include <tgmath.h>
#define PHI ((1 + sqrt(5))/2)
long long unsigned fib(unsigned n) {
return floor( (pow(PHI, n) - pow(1 - PHI, n))/sqrt(5) );
}

View file

@ -0,0 +1,37 @@
#include <stdio.h>
typedef enum{false=0, true=!0} bool;
typedef void iterator;
#include <setjmp.h>
/* declare label otherwise it is not visible in sub-scope */
#define LABEL(label) jmp_buf label; if(setjmp(label))goto label;
#define GOTO(label) longjmp(label, true)
/* the following line is the only time I have ever required "auto" */
#define FOR(i, iterator) { auto bool lambda(i); yield_init = (void *)&lambda; iterator; bool lambda(i)
#define DO {
#define YIELD(x) if(!yield(x))return
#define BREAK return false
#define CONTINUE return true
#define OD CONTINUE; } }
static volatile void *yield_init; /* not thread safe */
#define YIELDS(type) bool (*yield)(type) = yield_init
iterator fibonacci(int stop){
YIELDS(int);
int f[] = {0, 1};
int i;
for(i=0; i<stop; i++){
YIELD(f[i%2]);
f[i%2]=f[0]+f[1];
}
}
main(){
printf("fibonacci: ");
FOR(int i, fibonacci(16)) DO
printf("%d, ",i);
OD;
printf("...\n");
}

View file

@ -0,0 +1,28 @@
set_property(GLOBAL PROPERTY fibonacci_0 0)
set_property(GLOBAL PROPERTY fibonacci_1 1)
set_property(GLOBAL PROPERTY fibonacci_next 2)
# var = nth number in Fibonacci sequence.
function(fibonacci var n)
# If the sequence is too short, compute more Fibonacci numbers.
get_property(next GLOBAL PROPERTY fibonacci_next)
if(NOT next GREATER ${n})
# a, b = last 2 Fibonacci numbers
math(EXPR i "${next} - 2")
get_property(a GLOBAL PROPERTY fibonacci_${i})
math(EXPR i "${next} - 1")
get_property(b GLOBAL PROPERTY fibonacci_${i})
while(NOT next GREATER ${n})
math(EXPR i "${a} + ${b}") # i = next Fibonacci number
set_property(GLOBAL PROPERTY fibonacci_${next} ${i})
set(a ${b})
set(b ${i})
math(EXPR next "${next} + 1")
endwhile()
set_property(GLOBAL PROPERTY fibonacci_next ${next})
endif()
get_property(answer GLOBAL PROPERTY fibonacci_${n})
set(${var} ${answer} PARENT_SCOPE)
endfunction(fibonacci)

View file

@ -0,0 +1,12 @@
# Test program: print 0th to 9th and 25th to 30th Fibonacci numbers.
set(s "")
foreach(i RANGE 0 9)
fibonacci(f ${i})
set(s "${s} ${f}")
endforeach(i)
set(s "${s} ... ")
foreach(i RANGE 25 30)
fibonacci(f ${i})
set(s "${s} ${f}")
endforeach(i)
message(${s})

View file

@ -0,0 +1,6 @@
define fib {
dup 1 <=
[]
[dup 1 - fib swap 2 - fib +]
if
}

View file

@ -0,0 +1,31 @@
Stir-Fried Fibonacci Sequence.
An unobfuscated iterative implementation.
It prints the first N + 1 Fibonacci numbers,
where N is taken from standard input.
Ingredients.
0 g last
1 g this
0 g new
0 g input
Method.
Take input from refrigerator.
Put this into 4th mixing bowl.
Loop the input.
Clean the 3rd mixing bowl.
Put last into 3rd mixing bowl.
Add this into 3rd mixing bowl.
Fold new into 3rd mixing bowl.
Clean the 1st mixing bowl.
Put this into 1st mixing bowl.
Fold last into 1st mixing bowl.
Clean the 2nd mixing bowl.
Put new into 2nd mixing bowl.
Fold this into 2nd mixing bowl.
Put new into 4th mixing bowl.
Endloop input until looped.
Pour contents of the 4th mixing bowl into baking dish.
Serves 1.

View file

@ -0,0 +1,2 @@
(defn fibs []
(map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))

View file

@ -0,0 +1 @@
(nth (fibs) 5)

View file

@ -0,0 +1,6 @@
(defn fibs []
(map first ;; throw away the "metadata" (see below) to view just the fib numbers
(iterate ;; create an infinite sequence of [prev, curr] pairs
(fn [[a b]] ;; to produce the next pair, call this function on the current pair
[b (+ a b)]) ;; new prev is old curr, new curr is sum of both previous numbers
[0 1]))) ;; recursive base case: prev 0, curr 1

View file

@ -0,0 +1 @@
(def fib (lazy-cat [0 1] (map + fib (rest fib))))

View file

@ -0,0 +1,2 @@
user> (take 10 fib)
(0 1 1 2 3 5 8 13 21 34)

View file

@ -0,0 +1,18 @@
;; max is which fib number you'd like computed (0th, 1st, 2nd, etc.)
;; n is which fib number you're on for this call (0th, 1st, 2nd, etc.)
;; j is the nth fib number (ex. when n = 5, j = 5)
;; i is the nth - 1 fib number
(defn- fib-iter
[max n i j]
(if (= n max)
j
(recur max
(inc n)
j
(+ i j))))
(defn fib
[max]
(if (< max 2)
max
(fib-iter max 1 0N 1N)))

View file

@ -0,0 +1,4 @@
fib_ana = (n) ->
sqrt = Math.sqrt
phi = ((1 + sqrt(5))/2)
return Math.round((Math.pow(phi, n)/sqrt(5)))

View file

@ -0,0 +1,7 @@
fib_iter = (n) ->
if n < 2
return n
[prev, curr] = 0, 1
for i in [1..n]
[prev, curr] = [curr, curr + prev]
return curr

View file

@ -0,0 +1,5 @@
fib_rec = (n) ->
if n < 2
return n
else
return fib_rec(n-1) + fib_rec(n-2)

View file

@ -0,0 +1,4 @@
(defun fibonacci-recursive (n)
(if (< n 2)
n
(+ (fibonacci-recursive (- n 2)) (fibonacci-recursive (- n 1)))))

View file

@ -0,0 +1,8 @@
(defun fibonacci-iterative (n &aux (f0 0) (f1 1))
(case n
(0 f0)
(1 f1)
(t (loop for n from 2 to n
for a = f0 then b and b = f1 then result
for result = (+ a b)
finally (return result)))))

View file

@ -0,0 +1,4 @@
(defun fibonacci-tail-recursive ( n &optional (a 0) (b 1))
(if (= n 0)
a
(fibonacci-tail-recursive (- n 1) b (+ a b))))

View file

@ -0,0 +1,9 @@
(defun fib (n &optional (a 1) (b 0) (p 0) (q 1))
(if (= n 1) (+ (* b p) (* a q))
(fib (ash n -1)
(if (evenp n) a (+ (* b q) (* a (+ p q))))
(if (evenp n) b (+ (* b p) (* a q)))
(+ (* p p) (* q q))
(+ (* q q) (* 2 p q))))) ;p is Fib(2^n-1), q is Fib(2^n).
(print (fib 100000))

View file

@ -0,0 +1 @@
(loop for x = 0 then y and y = 1 then (+ x y) do (print x))

View file

@ -0,0 +1,89 @@
import std.stdio, std.conv, std.algorithm, std.math;
long sgn(alias unsignedFib)(int n) { // break sign manipulation apart
immutable uint m = (n >= 0) ? n : -n;
if (n < 0 && (n % 2 == 0))
return -unsignedFib(m);
else
return unsignedFib(m);
}
long fibD(uint m) { // Direct Calculation, correct for abs(m) <= 84
enum sqrt5r = 1.0L / sqrt(5.0L); // 1 / sqrt(5)
enum golden = (1.0L + sqrt(5.0L)) / 2.0L; // (1 + sqrt(5)) / 2
return roundTo!long(pow(golden, m) * sqrt5r);
}
long fibI(in uint m) pure nothrow { // Iterative
long thisFib = 0;
long nextFib = 1;
foreach (i; 0 .. m) {
long tmp = nextFib;
nextFib += thisFib;
thisFib = tmp;
}
return thisFib;
}
long fibR(uint m) { // Recursive
return (m < 2) ? m : fibR(m - 1) + fibR(m - 2);
}
long fibM(uint m) { // memoized Recursive
static long[] fib = [0, 1];
while (m >= fib.length )
fib ~= fibM(m - 2) + fibM(m - 1);
return fib[m];
}
alias sgn!fibD sfibD;
alias sgn!fibI sfibI;
alias sgn!fibR sfibR;
alias sgn!fibM sfibM;
auto fibG(in int m) { // generator(?)
immutable int sign = (m < 0) ? -1 : 1;
long yield;
return new class {
final int opApply(int delegate(ref int, ref long) dg) {
int idx = -sign; // prepare for pre-increment
foreach (f; this)
if (dg(idx += sign, f))
break;
return 0;
}
final int opApply(int delegate(ref long) dg) {
long f0, f1 = 1;
foreach (p; 0 .. m * sign + 1) {
if (sign == -1 && (p % 2 == 0))
yield = -f0;
else
yield = f0;
if (dg(yield)) break;
auto temp = f1;
f1 = f0 + f1;
f0 = temp;
}
return 0;
}
};
}
void main(in string[] args) {
int k = args.length > 1 ? to!int(args[1]) : 10;
writefln("Fib(%3d) = ", k);
writefln("D : %20d <- %20d + %20d",
sfibD(k), sfibD(k - 1), sfibD(k - 2));
writefln("I : %20d <- %20d + %20d",
sfibI(k), sfibI(k - 1), sfibI(k - 2));
if (abs(k) < 36 || args.length > 2)
// set a limit for recursive version
writefln("R : %20d <- %20d + %20d",
sfibR(k), sfibM(k - 1), sfibM(k - 2));
writefln("O : %20d <- %20d + %20d",
sfibM(k), sfibM(k - 1), sfibM(k - 2));
foreach (i, f; fibG(-9))
writef("%d:%d | ", i, f);
}

View file

@ -0,0 +1,30 @@
import std.stdio, std.bigint;
T fibonacciMatrix(T=BigInt)(size_t n) {
int[size_t.sizeof * 8] binDigits;
size_t nBinDigits;
while (n > 0) {
binDigits[nBinDigits] = n % 2;
n /= 2;
nBinDigits++;
}
T x=1, y, z=1;
foreach_reverse (b; binDigits[0 .. nBinDigits]) {
if (b) {
x = (x + z) * y;
y = y ^^ 2 + z ^^ 2;
} else {
auto x_old = x;
x = x ^^ 2 + y ^^ 2;
y = (x_old + z) * y;
}
z = x + y;
}
return y;
}
void main() {
writeln(fibonacciMatrix(1_000_000));
}

View file

@ -0,0 +1,5 @@
function fib(N : Integer) : Integer;
begin
if N < 2 then Result := 1
else Result := fib(N-2) + fib(N-1);
End;

View file

@ -0,0 +1,20 @@
int fib(int n) {
if(n==0 || n==1) {
return n;
}
int prev=1;
int current=1;
for(int i=2;i<n;i++) {
int next=prev+current;
prev=current;
current=next;
}
return current;
}
int fibRec(int n) => n==0||n==1 ? n : fibRec(n-1)+fibRec(n-2);
main() {
print(fib(11));
print(fibRec(11));
}

View file

@ -0,0 +1,18 @@
function FibonacciI(N: Word): UInt64;
var
Last, New: UInt64;
I: Word;
begin
if N < 2 then
Result := N
else begin
Last := 0;
Result := 1;
for I := 2 to N do
begin
New := Last + Result;
Last := Result;
Result := New;
end;
end;
end;

View file

@ -0,0 +1,7 @@
function Fibonacci(N: Word): UInt64;
begin
if N < 2 then
Result := N
else
Result := Fibonacci(N - 1) + Fibonacci(N - 2);
end;

View file

@ -0,0 +1,37 @@
function fib(n:Int64):int64;
type TFibMat = array[0..1] of array[0..1] of int64;
function FibMatMul(a,b:TFibMat):TFibMat;
var i,j,k:integer;
tmp:TFibMat;
begin
for i:=0 to 1 do
for j:=0 to 1 do
begin
tmp[i,j]:=0;
for k:=0 to 1 do tmp[i,j]:=tmp[i,j]+a[i,k]*b[k,j];
end;
FibMatMul:=tmp;
end;
function FibMatExp(a:TFibMat;n:int64):TFibmat;
begin
if n<=1 then fibmatexp:=a else
if (n mod 2 = 0) then FibMatExp:=FibMatExp(FibMatMul(a,a), n div 2) else
if (n mod 2 = 1) then FibMatExp:=FibMatMul(a,FibMatExp(FibMatMul(a,a),(n) div 2));
end;
var
matrix:TFibMat;
begin
matrix[0,0]:=1;
matrix[0,1]:=1;
matrix[1,0]:=1;
matrix[1,1]:=0;
if n>1 then
matrix:=fibmatexp(matrix,n-1);
fib:=matrix[0,0];
end;

View file

@ -0,0 +1,8 @@
def fib(n) {
var s := [0, 1]
for _ in 0..!n {
def [a, b] := s
s := [b, a+b]
}
return s[0]
}

View file

@ -0,0 +1,3 @@
fib = fib' 0 1
where fib' a b 0 = a
fib' a b n = fib' b (a + b) (n - 1)

View file

@ -0,0 +1,2 @@
fib = fib' 1 1
where fib' x y = & x :: fib' y (x + y)

View file

@ -0,0 +1,3 @@
fib(0) -> 0;
fib(1) -> 1;
fib(N) when N > 1 -> fib(N-1) + fib(N-2).

View file

@ -0,0 +1,3 @@
fib(N) -> fib(N,0,1).
fib(0,Res,_) -> Res;
fib(N,Res,Next) when N > 0 -> fib(N-1, Next, Res+Next).

View file

@ -0,0 +1,4 @@
function fibor(integer n)
if n<2 then return n end if
return fibor(n-1)+fibor(n-2)
end function

View file

@ -0,0 +1,10 @@
function fiboi(integer n)
integer f0=0, f1=1, f
if n<2 then return n end if
for i=2 to n do
f=f0+f1
f0=f1
f1=f
end for
return f
end function

View file

@ -0,0 +1,10 @@
function fibot(integer n, integer u = 1, integer s = 0)
if n < 1 then
return s
else
return fibot(n-1,u+s,u)
end if
end function
-- example:
? fibot(10) -- says 55

View file

@ -0,0 +1,78 @@
include std/mathcons.e -- for PINF constant
enum ADD, MOVE, GOTO, OUT, TEST, TRUETO
global sequence tape = { 0,
1,
{ ADD, 2, 1 },
{ TEST, 1, PINF },
{ TRUETO, 0 },
{ OUT, 1, "%.0f\n" },
{ MOVE, 2, 1 },
{ MOVE, 0, 2 },
{ GOTO, 3 } }
global integer ip
global integer test
global atom accum
procedure eval( sequence cmd )
atom i = 1
while i <= length( cmd ) do
switch cmd[ i ] do
case ADD then
accum = tape[ cmd[ i + 1 ] ] + tape[ cmd[ i + 2 ] ]
i += 2
case OUT then
printf( 1, cmd[ i + 2], tape[ cmd[ i + 1 ] ] )
i += 2
case MOVE then
if cmd[ i + 1 ] = 0 then
tape[ cmd[ i + 2 ] ] = accum
else
tape[ cmd[ i + 2 ] ] = tape[ cmd[ i + 1 ] ]
end if
i += 2
case GOTO then
ip = cmd[ i + 1 ] - 1 -- due to ip += 1 in main loop
i += 1
case TEST then
if tape[ cmd[ i + 1 ] ] = cmd[ i + 2 ] then
test = 1
else
test = 0
end if
i += 2
case TRUETO then
if test then
if cmd[ i + 1 ] = 0 then
abort(0)
else
ip = cmd[ i + 1 ] - 1
end if
end if
end switch
i += 1
end while
end procedure
test = 0
accum = 0
ip = 1
while 1 do
-- embedded sequences (assumed to be code) are evaluated
-- atoms (assumed to be data) are ignored
if sequence( tape[ ip ] ) then
eval( tape[ ip ] )
end if
ip += 1
end while

View file

@ -0,0 +1,3 @@
[[$0=~][1-@@\$@@+\$44,.@]#]f:
20n: {First 20 numbers}
0 1 n;f;!%%44,. {Output: "0,1,1,2,3,5..."}

View file

@ -0,0 +1,5 @@
: fib ( n -- m )
dup 2 < [
[ 0 1 ] dip [ swap [ + ] keep ] times
drop
] unless ;

View file

@ -0,0 +1,4 @@
: fib ( n -- m )
dup 2 < [
[ 1 - fib ] [ 2 - fib ] bi +
] unless ;

View file

@ -0,0 +1,6 @@
: fib2 ( x y n -- a )
dup 1 <
[ 2drop ]
[ [ swap [ + ] keep ] dip 1 - fib2 ]
if ;
: fib ( n -- m ) [ 0 1 ] dip fib2 ;

View file

@ -0,0 +1,7 @@
USE: math.matrices
: fib ( n -- m )
dup 2 < [
[ { { 0 1 } { 1 1 } } ] dip 1 - m^n
second second
] unless ;

View file

@ -0,0 +1,13 @@
function fib_i(n)
if n < 2: return n
fibPrev = 1
fib = 1
for i in [2:n]
tmp = fib
fib += fibPrev
fibPrev = tmp
end
return fib
end

View file

@ -0,0 +1,4 @@
function fib_r(n)
if n < 2 : return n
return fib_r(n-1) + fib_r(n-2)
end

View file

@ -0,0 +1,9 @@
function fib_tr(n)
return fib_aux(n,0,1)
end
function fib_aux(n,a,b)
switch n
case 0 : return a
default: return fib_aux(n-1,a+b,a)
end
end

View file

@ -0,0 +1,13 @@
class Fixnum {
def fib {
match self -> {
case 0 -> 0
case 1 -> 1
case _ -> self - 1 fib + (self - 2 fib)
}
}
}
15 times: |x| {
x fib println
}

View file

@ -0,0 +1,21 @@
class Main
{
static Int fib (Int n)
{
if (n < 2) return n
fibNums := [1, 0]
while (fibNums.size <= n)
{
fibNums.insert (0, fibNums[0] + fibNums[1])
}
return fibNums.first
}
public static Void main ()
{
20.times |n|
{
echo ("Fib($n) is ${fib(n)}")
}
}
}

View file

@ -0,0 +1,26 @@
# fibonacci is the infinite list of all Fibonacci numbers.
#
# Note that this program uses the symbols "1" and "+". You can specify
# the definitions of those symbols however you like, allowing you to use
# any system of arithmetic you need. For example, you can use either the
# built-in long arithmetic, or infinite precision arithmetic, by simply
# defining "1" and "+" appropriately.
\fibonacci =
(
\fibonacci == (\x\y
item x;
\z = (+ x y)
fibonacci y z
)
fibonacci 1 1
)
# OK, so that's the list of *all* Fibonacci numbers. If you want the nth number,
# you can extract it with the fib function as follows. By the way, this *does*
# have the effect of caching, so once a particular point in the sequence is
# calculated, it doesn't have to be calculated again.
# (fib n) is the nth fibonacci number, starting with n==0, or 1 if n is negative.
\fib = (\n list_at fibonacci n 1)

View file

@ -0,0 +1,2 @@
: fib ( n -- fib )
0 1 rot 0 ?do over + swap loop drop ;

View file

@ -0,0 +1,12 @@
module fibonacci
contains
recursive function fibR(n) result(fib)
integer, intent(in) :: n
integer :: fib
select case (n)
case (:0); fib = 0
case (1); fib = 1
case default; fib = fibR(n-1) + fibR(n-2)
end select
end function fibR

View file

@ -0,0 +1,20 @@
function fibI(n)
integer, intent(in) :: n
integer, parameter :: fib0 = 0, fib1 = 1
integer :: fibI, back1, back2, i
select case (n)
case (:0); fibI = fib0
case (1); fibI = fib1
case default
fibI = fib1
back1 = fib0
do i = 2, n
back2 = back1
back1 = fibI
fibI = back1 + back2
end do
end select
end function fibI
end module fibonacci

View file

@ -0,0 +1,7 @@
program fibTest
use fibonacci
do i = 0, 10
print *, fibr(i), fibi(i)
end do
end program fibTest

View file

@ -0,0 +1,5 @@
fib := function(n)
local a;
a := [[0, 1], [1, 1]]^n;
return a[1][2];
end;

View file

@ -0,0 +1 @@
Fibonacci(n);

View file

@ -0,0 +1 @@
0 1 dup wover + dup wover + dup wover + dup wover +

Some files were not shown because too many files have changed in this diff Show more