Data update

This commit is contained in:
Ingy döt Net 2026-02-01 16:33:20 -08:00
parent 5150844a7d
commit 4bb20c9b71
7735 changed files with 38060 additions and 199180 deletions

View file

@ -2,23 +2,27 @@ The '''Fibonacci sequence''' is a sequence &nbsp; <big> F<sub>n</sub> </big> &nb
<big><big> F<sub>0</sub> = 0 </big></big>
<big><big> F<sub>1</sub> = 1 </big></big>
<big><big> F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub>, if n>1 </big></big>
<big><big> F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub> , if n > 1 </big></big>
;Task:
Write a function to generate the &nbsp; <big> n<sup>th</sup> </big> &nbsp; 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).
Solutions can be iterative, recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion), or use [https://en.wikipedia.org/wiki/Fibonacci_sequence#Binet's_formula Binet's algebraic formula].
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
The sequence is sometimes extended for negative numbers by using an alternating inverse of the positive values. Rewriting the definition as
<big><big> F<sub>n</sub> = F<sub>n+2</sub> - F<sub>n+1</sub>, if n<0 </big></big>
<big><big> F<sub>n</sub> = F<sub>n+2</sub> - F<sub>n+1</sub> , if n < 0 </big></big>
support for negative &nbsp; &nbsp; <big> n </big> &nbsp; &nbsp; in the solution is optional.
leads to
<big><big> F<sub>-n</sub> = (-1)<sup>n+1</sup> F<sub>n</sub> </big></big>.
Support for negative <big> n </big> in the solution is optional.
;Related tasks:
* &nbsp; [[Fibonacci n-step number sequences]]
* &nbsp; [[Fibonacci n-step number sequences]]
* &nbsp; [[Leonardo numbers]]

View file

@ -1,19 +0,0 @@
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

@ -1,20 +0,0 @@
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

@ -1,33 +0,0 @@
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

@ -1,49 +0,0 @@
with ada.text_io;
use ada.text_io;
procedure fast_fibo is
-- We work with biggest natural integers in a 64 bits machine
type Big_Int is mod 2**64;
-- We provide an index type for accessing the fibonacci sequence terms
type Index is new Big_Int;
-- fibo is a generic function that needs a modulus type since it will return
-- the n'th term of the fibonacci sequence modulus this type (use Big_Int to get the
-- expected behaviour in this particular task)
generic
type ring_element is mod <>;
with function "*" (a, b : ring_element) return ring_element is <>;
function fibo (n : Index) return ring_element;
function fibo (n : Index) return ring_element is
type matrix is array (1 .. 2, 1 .. 2) of ring_element;
-- f is the matrix you apply to a column containing (F_n, F_{n+1}) to get
-- the next one containing (F_{n+1},F_{n+2})
-- could be a more general matrix (given as a generic parameter) to deal with
-- other linear sequences of order 2
f : constant matrix := (1 => (0, 1), 2 => (1, 1));
function "*" (a, b : matrix) return matrix is
(1 => (a(1,1)*b(1,1)+a(1,2)*b(2,1), a(1,1)*b(1,2)+a(1,2)*b(2,2)),
2 => (a(2,1)*b(1,1)+a(2,2)*b(2,1), a(2,1)*b(1,2)+a(2,2)*b(2,2)));
function square (m : matrix) return matrix is (m * m);
-- Fast_Pow could be non recursive but it doesn't really matter since
-- the number of calls is bounded up by the size (in bits) of Big_Int (e.g 64)
function fast_pow (m : matrix; n : Index) return matrix is
(if n = 0 then (1 => (1, 0), 2 => (0, 1)) -- = identity matrix
elsif n mod 2 = 0 then square (fast_pow (m, n / 2))
else m * square (fast_pow (m, n / 2)));
begin
return fast_pow (f, n)(2, 1);
end fibo;
function Big_Int_Fibo is new fibo (Big_Int);
begin
-- calculate instantly F_n with n=10^15 (modulus 2^64 )
put_line (Big_Int_Fibo (10**15)'img);
end fast_fibo;

View file

@ -1,8 +0,0 @@
fib: $[x][
if? x<2 [1]
else [(fib x-1) + (fib x-2)]
]
loop 1..25 [x][
print ["Fibonacci of" x "=" fib x]
]

View file

@ -1,27 +0,0 @@
#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

@ -1,19 +0,0 @@
#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

@ -1,40 +0,0 @@
Program-ID. Fibonacci-Sequence.
Data Division.
Working-Storage Section.
01 FIBONACCI-PROCESSING.
05 FIBONACCI-NUMBER PIC 9(36) VALUE 0.
05 FIB-ONE PIC 9(36) VALUE 0.
05 FIB-TWO PIC 9(36) VALUE 1.
01 DESIRED-COUNT PIC 9(4).
01 FORMATTING.
05 INTERM-RESULT PIC Z(35)9.
05 FORMATTED-RESULT PIC X(36).
05 FORMATTED-SPACE PIC x(35).
Procedure Division.
000-START-PROGRAM.
Display "What place of the Fibonacci Sequence would you like (<173)? " with no advancing.
Accept DESIRED-COUNT.
If DESIRED-COUNT is less than 1
Stop run.
If DESIRED-COUNT is less than 2
Move FIBONACCI-NUMBER to INTERM-RESULT
Move INTERM-RESULT to FORMATTED-RESULT
Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT
Display FORMATTED-RESULT
Stop run.
Subtract 1 from DESIRED-COUNT.
Move FIBONACCI-NUMBER to INTERM-RESULT.
Move INTERM-RESULT to FORMATTED-RESULT.
Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT.
Display FORMATTED-RESULT.
Perform 100-COMPUTE-FIBONACCI until DESIRED-COUNT = zero.
Stop run.
100-COMPUTE-FIBONACCI.
Compute FIBONACCI-NUMBER = FIB-ONE + FIB-TWO.
Move FIB-TWO to FIB-ONE.
Move FIBONACCI-NUMBER to FIB-TWO.
Subtract 1 from DESIRED-COUNT.
Move FIBONACCI-NUMBER to INTERM-RESULT.
Move INTERM-RESULT to FORMATTED-RESULT.
Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT.
Display FORMATTED-RESULT.

View file

@ -1,45 +0,0 @@
>>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. fibonacci-main.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 num PIC 9(6) COMP.
01 fib-num PIC 9(6) COMP.
PROCEDURE DIVISION.
ACCEPT num
CALL "fibonacci" USING CONTENT num RETURNING fib-num
DISPLAY fib-num
.
END PROGRAM fibonacci-main.
IDENTIFICATION DIVISION.
PROGRAM-ID. fibonacci RECURSIVE.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 1-before PIC 9(6) COMP.
01 2-before PIC 9(6) COMP.
LINKAGE SECTION.
01 num PIC 9(6) COMP.
01 fib-num PIC 9(6) COMP BASED.
PROCEDURE DIVISION USING num RETURNING fib-num.
ALLOCATE fib-num
EVALUATE num
WHEN 0
MOVE 0 TO fib-num
WHEN 1
MOVE 1 TO fib-num
WHEN OTHER
SUBTRACT 1 FROM num
CALL "fibonacci" USING CONTENT num RETURNING 1-before
SUBTRACT 1 FROM num
CALL "fibonacci" USING CONTENT num RETURNING 2-before
ADD 1-before TO 2-before GIVING fib-num
END-EVALUATE
.
END PROGRAM fibonacci.

View file

@ -1,8 +0,0 @@
iter fib() {
var a = 0, b = 1;
while true {
yield a;
(a, b) = (b, b + a);
}
}

View file

@ -1,8 +0,0 @@
Fixpoint rec_fib (m : nat) (a : nat) (b : nat) : nat :=
match m with
| 0 => a
| S k => rec_fib k b (a + b)
end.
Definition fib (n : nat) : nat :=
rec_fib n 0 1 .

View file

@ -1,8 +1,5 @@
func fib n .
if n < 2
return n
.
prev = 0
if n < 2 : return n
val = 1
for i = 2 to n
h = prev + val

View file

@ -1,7 +1,5 @@
func fib n .
if n < 2
return n
.
if n < 2 : return n
return fib (n - 2) + fib (n - 1)
.
print fib 36

View file

@ -20,7 +20,7 @@ fibu(n)
}
}
public program()
public Program()
{
for(int i := 0; i <= 10; i+=1)
{

View file

@ -25,7 +25,7 @@ singleton FibonacciEnumerable : Enumerable
}
}
public program()
public Program()
{
auto e := FibonacciEnumerable.enumerator();

View file

@ -1,10 +0,0 @@
(defun fib (n a b c)
(cond
((< c n) (fib n b (+ a b) (+ 1 c)))
((= c n) b)
(t a)))
(defun fibonacci (n)
(if (< n 2)
n
(fib n 0 1 1)))

View file

@ -1,15 +0,0 @@
(defun fibonacci (n)
(let (vec i j k)
(if (< n 2)
n
(setq vec (make-vector (+ n 1) 0)
i 0
j 1
k 2)
(setf (aref vec 1) 1)
(while (<= k n)
(setf (aref vec k) (+ (elt vec i) (elt vec j)))
(setq i (1+ i)
j (1+ j)
k (1+ k)))
(elt vec n))))

View file

@ -1,3 +0,0 @@
(insert
(mapconcat (lambda (n) (format "%d" (fibonacci n)))
(number-sequence 0 15) " "))

View file

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

View file

@ -1,10 +0,0 @@
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

@ -1,10 +0,0 @@
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

@ -1,78 +0,0 @@
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

@ -1,3 +1,30 @@
function fibfc(n) result(f) ! integer forward count using 128 bit integers.
! DOMAIN: up to 184
! uses 16 byte integers
integer(16), intent (in) :: n ! input
integer(16) :: f ! output
integer(16) :: i, fm2, fm1
if (n>184) then
PRINT *, "ERROR: 'a' must be in the domain 0 <= n <= 184 !"
STOP
end if
f=0
fm2=0
fm1=1
IF ( n > 0 ) f = 1
IF ( n < 3 ) return
do i = 2, n
f=fm2+fm1
fm2=fm1
fm1=f
enddo
end function
</syntaxhighlight lang="fortran">
===FORTRAN 77===
<syntaxhighlight lang="fortran">
FUNCTION IFIB(N)
IF (N.EQ.0) THEN
ITEMP0=0

View file

@ -1,15 +0,0 @@
static function fib(steps:Int, handler:Int->Void)
{
var current = 0;
var next = 1;
for (i in 1...steps)
{
handler(current);
var temp = current + next;
current = next;
next = temp;
}
handler(current);
}

View file

@ -1,19 +0,0 @@
class FibIter
{
private var current = 0;
private var nextItem = 1;
private var limit:Int;
public function new(limit) this.limit = limit;
public function hasNext() return limit > 0;
public function next() {
limit--;
var ret = current;
var temp = current + nextItem;
current = nextItem;
nextItem = temp;
return ret;
}
}

View file

@ -1,2 +0,0 @@
for (i in new FibIter(10))
Sys.println(i);

View file

@ -1,3 +0,0 @@
val fibonacci = fn x:if(x < 2: x ; fn((x - 1)) + fn((x - 2)))
writeln map(series(2..20), by=fibonacci)

File diff suppressed because it is too large Load diff

View file

@ -1,8 +1,17 @@
function fib(n: integer): integer;
begin
if (n = 0) or (n = 1)
then
fib := n
else
fib := fib(n-1) + fib(n-2)
end;
function fib(n: integer):longInt;
const
Sqrt5 = sqrt(5.0);
C1 = ln((Sqrt5+1.0)*0.5);//ln( 1.618..)
//C2 = ln((1.0-Sqrt5)*0.5);//ln(-0.618 )) tsetsetse
C2 = ln((Sqrt5-1.0)*0.5);//ln(+0.618 ))
begin
IF n>0 then
begin
IF odd(n) then
fib := round((exp(C1*n) + exp(C2*n) )/Sqrt5)
else
fib := round((exp(C1*n) - exp(C2*n) )/Sqrt5)
end
else
Fibdirekt := 0
end;

View file

@ -1,22 +1,8 @@
function fib(n: integer): integer;
var
f0, f1, tmpf0, k: integer;
begin
f1 := n;
IF f1 >1 then
begin
k := f1-1;
f0 := 0;
f1 := 1;
repeat
tmpf0 := f0;
f0 := f1;
f1 := f1+tmpf0;
dec(k);
until k = 0;
end
else
IF f1 < 0 then
f1 := 0;
fib := f1;
end;
begin
if (n = 0) or (n = 1)
then
fib := n
else
fib := fib(n-1) + fib(n-2)
end;

View file

@ -1,4 +1,22 @@
function FiboMax(n: integer):Extended; //maXbox
function fib(n: integer): integer;
var
f0, f1, tmpf0, k: integer;
begin
result:= (pow((1+SQRT5)/2,n)-pow((1-SQRT5)/2,n))/SQRT5
f1 := n;
IF f1 >1 then
begin
k := f1-1;
f0 := 0;
f1 := 1;
repeat
tmpf0 := f0;
f0 := f1;
f1 := f1+tmpf0;
dec(k);
until k = 0;
end
else
IF f1 < 0 then
f1 := 0;
fib := f1;
end;

View file

@ -1,18 +1,4 @@
function Fibo_BigInt(n: integer): string; //maXbox
var tbig1, tbig2, tbig3: TInteger;
begin
result:= '0'
tbig1:= TInteger.create(1); //temp
tbig2:= TInteger.create(0); //result (a)
tbig3:= Tinteger.create(1); //b
for it:= 1 to n do begin
tbig1.assign(tbig2)
tbig2.assign(tbig3);
tbig1.add(tbig3);
tbig3.assign(tbig1);
end;
result:= tbig2.toString(false)
tbig3.free;
tbig2.free;
tbig1.free;
end;
function FiboMax(n: integer):Extended; //maXbox
begin
result:= (pow((1+SQRT5)/2,n)-pow((1-SQRT5)/2,n))/SQRT5
end;

View file

@ -1,62 +1,18 @@
program Fibonacci_console;
{$mode objfpc}{$H+}
uses SysUtils;
function Fibonacci( n : word) : uint64;
{
Starts with the pair F[0],F[1]. At each iteration, uses the doubling formulae
to pass from F[k],F[k+1] to F[2k],F[2k+1]. If the current bit of n (starting
from the high end) is 1, there is a further step to F[2k+1],F[2k+2].
}
var
marker, half_n : word;
f, g : uint64; // pair of consecutive Fibonacci numbers
t, u : uint64; // -----"-----
begin
// The values of F[0], F[1], F[2] are assumed to be known
case n of
0 : result := 0;
1, 2 : result := 1;
else begin
half_n := n shr 1;
marker := 1;
while marker <= half_n do marker := marker shl 1;
// First time: current bit is 1 by construction,
// so go straight from F[0],F[1] to F[1],F[2].
f := 1; // = F[1]
g := 1; // = F[2]
marker := marker shr 1;
while marker > 1 do begin
t := f*(2*g - f);
u := f*f + g*g;
if (n and marker = 0) then begin
f := t;
g := u;
end
else begin
f := u;
g := t + u;
end;
marker := marker shr 1;
end;
// Last time: we need only one of the pair.
if (n and marker = 0) then
result := f*(2*g - f)
else
result := f*f + g*g;
end; // end else (i.e. n > 2)
end; // end case
end;
// Main program
var
n : word;
begin
for n := 0 to 93 do
WriteLn( SysUtils.Format( 'F[%2u] = %20u', [n, Fibonacci(n)]));
end.
function Fibo_BigInt(n: integer): string; //maXbox
var tbig1, tbig2, tbig3: TInteger;
begin
result:= '0'
tbig1:= TInteger.create(1); //temp
tbig2:= TInteger.create(0); //result (a)
tbig3:= Tinteger.create(1); //b
for it:= 1 to n do begin
tbig1.assign(tbig2)
tbig2.assign(tbig3);
tbig1.add(tbig3);
tbig3.assign(tbig1);
end;
result:= tbig2.toString(false)
tbig3.free;
tbig2.free;
tbig1.free;
end;

View file

@ -1,9 +0,0 @@
function FibonacciNumber ( $count )
{
$answer = @(0,1)
while ($answer.Length -le $count)
{
$answer += $answer[-1] + $answer[-2]
}
return $answer
}

View file

@ -1,4 +0,0 @@
$count = 8
$answer = @(0,1)
0..($count - $answer.Length) | Foreach { $answer += $answer[-1] + $answer[-2] }
$answer

View file

@ -1,8 +0,0 @@
function fib($n) {
switch ($n) {
0 { return 0 }
1 { return 1 }
{ $_ -lt 0 } { return [Math]::Pow(-1, -$n + 1) * (fib (-$n)) }
default { return (fib ($n - 1)) + (fib ($n - 2)) }
}
}

View file

@ -1,6 +1,8 @@
from math import *
def analytic_fibonacci(n):
assert isinstance(n,int), "n must be an integer."
assert n<=71 , "n must be <=71 due to floating point precision limitations."
sqrt_5 = sqrt(5);
p = (1 + sqrt_5) / 2;
q = 1/p;

View file

@ -1,7 +1,31 @@
def fib(n, c={0:1, 1:1}):
if n not in c:
x = n // 2
c[n] = fib(x-1) * fib(n-x-1) + fib(x) * fib(n - x)
return c[n]
def prev_pow_two(n):
"""Gets the power of two that is less than or equal to the given input
"""
if ((n & -n) == n):
return n
n -= 1
n |= n >> 1
n |= n >> 2
n |= n >> 4
n |= n >> 8
n |= n >> 16
n += 1
return n//2
fib(10000000) # calculating it takes a few seconds, printing it takes eons
def crazy_fib(n):
"""Crazy fast fibonacci number calculation
"""
pow_two = prev_pow_two(n)
q = r = i = 1
s = 0
while i < pow_two:
i *= 2
q, r, s = q*q + r*r, r * (q + s), (r*r + s*s)
while i < n:
i += 1
q, r, s = q+r, q, r
return q

View file

@ -1,8 +1,7 @@
F = {0: 0, 1: 1, 2: 1}
def fib(n):
if n in F:
return F[n]
f1 = fib(n // 2 + 1)
f2 = fib((n - 1) // 2)
F[n] = (f1 * f1 + f2 * f2 if n & 1 else f1 * f1 - f2 * f2)
return F[n]
def fib(n, c={0:1, 1:1}):
if n not in c:
x = n // 2
c[n] = fib(x-1) * fib(n-x-1) + fib(x) * fib(n - x)
return c[n]
fib(10000000) # calculating it takes a few seconds, printing it takes eons

View file

@ -1,10 +1,8 @@
def fib():
"""Yield fib[n+1] + fib[n]"""
yield 1 # have to start somewhere
lhs, rhs = fib(), fib()
yield next(lhs) # move lhs one iteration ahead
while True:
yield next(lhs)+next(rhs)
f=fib()
print [next(f) for _ in range(9)]
F = {0: 0, 1: 1, 2: 1}
def fib(n):
if n in F:
return F[n]
f1 = fib(n // 2 + 1)
f2 = fib((n - 1) // 2)
F[n] = (f1 * f1 + f2 * f2 if n & 1 else f1 * f1 - f2 * f2)
return F[n]

View file

@ -1,11 +1,11 @@
from itertools import islice
def fib():
yield 0
"""Yield fib[n+1] + fib[n]"""
yield 1
a, b = fib(), fib()
next(b)
lhs, rhs = fib(), fib()
# move lhs one iteration ahead
yield next(lhs)
while True:
yield next(a)+next(b)
yield next(lhs)+next(rhs)
print(tuple(islice(fib(), 10)))
f=fib()
print [next(f) for _ in range(9)]

View file

@ -1,23 +1,11 @@
'''Fibonacci accumulation'''
from itertools import islice
from itertools import accumulate
def fib():
yield 0
yield 1
a, b = fib(), fib()
next(b)
while True:
yield next(a)+next(b)
# fibs :: Integer :: [Integer]
def fibs(n):
'''An accumulation of the first n integers in
the Fibonacci series. The accumulator is a
pair of the two preceding numbers.
'''
return [
a
for a, b in accumulate(
range(1, n), # we don't actually use these numbers
lambda acc, _: (acc[1], sum(acc)),
initial = (0, 1)
)
]
# MAIN ---
if __name__ == '__main__':
print(f'First twenty: {fibs(20)}')
print(tuple(islice(fib(), 10)))

View file

@ -1,18 +1,21 @@
'''Nth Fibonacci term (by folding)'''
def fibs(n):
"""Fibonacci accumulation
from functools import reduce
An accumulation of the first n integers in the Fibonacci series. The accumulator is a
pair of the two preceding numbers.
"""
# Local import is more efficient.
from itertools import accumulate
# nthFib :: Integer -> Integer
def nthFib(n):
'''Nth integer in the Fibonacci series.'''
return reduce(
lambda acc, _: (acc[1], sum(acc)),
# Note: Numbers generated in range(1, n) [or range(n-1)] call will not be used.
return [a for a, b in accumulate(
range(1, n),
(0, 1)
)[0]
lambda acc, _: (acc[1], sum(acc)),
initial = (0, 1)
)
]
# MAIN ---
if __name__ == '__main__':
n = 1000
print(f'{n}th term: {nthFib(n)}')
print(f'First twenty: {fibs(20)}')

View file

@ -1,3 +1,17 @@
def fib(n):
def nth_fib(n):
"""Nth Fibonacci term (by folding)
Nth integer in the Fibonacci series.
"""
from functools import reduce
return reduce(lambda x, y: (x[1], x[0] + x[1]), range(n), (0, 1))[0]
return reduce(
lambda acc, _: (acc[1], sum(acc)),
range(1, n),
(0, 1)
)[0]
# MAIN ---
if __name__ == '__main__':
n = 1000
print(f'{n}th term: {nth_fib(n)}')

View file

@ -1,6 +1,3 @@
fibseq = [1,1,]
fiblength = 21
for x in range(1,fiblength-1):
xcount = fibseq[x-1] + fibseq[x]
fibseq.append(xcount)
print(xcount)
def fib(n):
from functools import reduce
return reduce(lambda x, y: (x[1], x[0] + x[1]), range(n), (0, 1))[0]

View file

@ -1,8 +1,28 @@
def fibIter(n):
if n < 2:
return n
fibPrev = 1
fib = 1
for _ in range(2, n):
fibPrev, fib = fib, fib + fibPrev
return fib
def analytic_fibonacci91(m):
"""
Binet's algebraic formula for the nth Fibonacci number.
Good for up to n=91
Uses numpy longdoubles:
See: https://artofproblemsolving.com/wiki/index.php/Binet%27s_Formula
"""
import numpy as np
assert isinstance(m,int), "parameter must be an integer."
assert 0<=m<=91 , "n must be in the range 0 .. 91 due to double precision floating point precision limitations."
if m < 2: return m
# Make sure that nothing causes conversion to single
n=np.longdouble(m)
C1=np.longdouble(1)
C2=np.longdouble(2)
C5=np.longdouble(5)
Chalf=C1/C2
Cfifth=C1/C5
root5=C5**Chalf
t1=(C1+root5)/C2
t2=(C1-root5)/C2
f=(t1**n-t2**n)/root5
return int(f+0.1)
# Usage
print(f:=[[i,analytic_fibonacci91(i)] for i in range(92)])

View file

@ -1,5 +1,60 @@
def fib(n,x=[0,1]):
for i in range(abs(n)-1): x=[x[1],sum(x)]
return x[1]*pow(-1,abs(n)-1) if n<0 else x[1] if n else 0
def fib4k(n): # FIBonacci's numbers, Binet's Formula, Barron's Binomial expansion, Kra's code.
# (c) 2025 David A. Kra GNUFDL1.3 and Copyleft Creative Commons CC BY-SA Attribution-ShareAlike
#
# ALL INTEGER. Tested up to Fib(4000).
# NOTE: This implementation is NOT faster than simply progressing up to Fib(n) by addition, starting from Fib(1).
# Thanks, Acknowledgement, and Appreciation to Barron https://stackexchange.com/users/9594318/barron
# No floats were exploited in the production of this function.
# References:
# https://math.stackexchange.com/questions/674570/prove-that-binets-formula-gives-an-integer-using-the-binomial-theorem
# https://math.stackexchange.com/questions/2002702/fibonacci-identity-with-binomial-coefficients
# https://artofproblemsolving.com/wiki/index.php/Binet%27s_Formula
# https://latex.artofproblemsolving.com/8/6/d/86d486c560727727342090b432e23ba85ac098b1.png
# https://www.geeksforgeeks.org/find-nth-fibonacci-number-using-binets-formula/
# https://discuss.geeksforgeeks.org/comment/540dc728-8cfc-41e3-853e-e920e0a85101/gfg
# # Fn=(1/(2**(n-1))) * SUM(j=0,n//2,((5**j)*comb(n,2*j+1))
#
# qc == Quick Combination. Instead of using comb, with its loop on each call,
# derive the next ( comb(n,2*j+1) ) by building up from what had already been calculated,
# Given comb(n,2*j+1), then
# comb(n,2*(j+1)+1) = comb(n,2*j+1) * (n-(2*j+1))*(n-2*j+1)-1) // ( (2*j+1)+1)*(2*j+1)+2) )
# qp == Quick Power. Instead of using 5**j, derive the next fttj as fttj*=5
#
f=0
fttj=1
qc=n # = comb(n,1)
for j in range(0,int(n/2+1)):
f+=fttj*qc # (5**k)*qc # qc == comb(n,2*k+1)
j2p1=j*2+1
# calculate the 5**k and the combinations for the next iteration,
# but for now, k and k2p1 have this iteration's values.
fttj*=5
qc=qc* (n-j2p1)*(n-j2p1-1) // ( (j2p1+1)*(j2p1+2) ) # for the next iteration
for i in range(-30,31): print fib(i),
f=f//(2 ** (n-1) )
return f
</syntaxhighlight lang="python">
<pre>
Test
print([[i,fib4k(i)] for i in [4,40,400,4000]])
output
[[4, 3], [40, 102334155], [400, 176023680645013966468226945392411250770384383304492191886725992896575345044216019675], [4000, 39909473435004422792081248094960912600792570982820257852628876326523051818641373433549136769424132442293969306537520118273879628025443235370362250955435654171592897966790864814458223141914272590897468472180370639695334449662650312874735560926298246249404168309064214351044459077749425236777660809226095151852052781352975449482565838369809183771787439660825140502824343131911711296392457138867486593923544177893735428602238212249156564631452507658603400012003685322984838488962351492632577755354452904049241294565662519417235020049873873878602731379207893212335423484873469083054556329894167262818692599815209582517277965059068235543139459375028276851221435815957374273143824422909416395375178739268544368126894240979135322176080374780998010657710775625856041594078495411724236560242597759185543824798332467919613598667003025993715274875]]
</pre>
===Iterative===
<syntaxhighlight lang="python">def fib_iter(n):
if n < 2:
return n
fib_prev = 1
fib = 1
for _ in range(2, n):
fib_prev, fib = fib, fib + fib_prev
return fib

View file

@ -1,5 +1,5 @@
def fibRec(n):
if n < 2:
return n
else:
return fibRec(n-1) + fibRec(n-2)
def fib(n,x=[0,1]):
for i in range(abs(n)-1): x=[x[1],sum(x)]
return x[1]*pow(-1,abs(n)-1) if n<0 else x[1] if n else 0
for i in range(-30,31): print fib(i),

View file

@ -1,11 +1,4 @@
def fibMemo():
pad = {0:0, 1:1}
def func(n):
if n not in pad:
pad[n] = func(n-1) + func(n-2)
return pad[n]
return func
fm = fibMemo()
for i in range(1,31):
print fm(i),
def fib_rec(n):
if n < 2:
return n
return fib_rec(n-1) + fib_rec(n-2)

View file

@ -1,7 +1,11 @@
def fibFastRec(n):
def fib(prvprv, prv, c):
if c < 1:
return prvprv
else:
return fib(prv, prvprv + prv, c - 1)
return fib(0, 1, n)
def fib_memo():
pad = {0:0, 1:1}
def sub_func(n):
if not n in pad:
pad[n] = sub_func(n-1) + sub_func(n-2)
return pad[n]
return sub_func
fm = fib_memo()
for i in range(1,31):
print(fm(i))

View file

@ -1,5 +1,6 @@
def fibGen(n):
a, b = 0, 1
while n>0:
yield a
a, b, n = b, a+b, n-1
def fib_fast_rec(n):
def inner_fib(prvprv, prv, c):
if c < 1:
return prvprv
return inner_fib(prv, prvprv + prv, c - 1)
return inner_fib(0, 1, n)

View file

@ -1,3 +1,5 @@
>>> [i for i in fibGen(11)]
[0,1,1,2,3,5,8,13,21,34,55]
def fib_gen(n):
a, b = 0, 1
while n>0:
yield a
a, b, n = b, a+b, n-1

View file

@ -1,30 +1,3 @@
def prevPowTwo(n):
'Gets the power of two that is less than or equal to the given input'
if ((n & -n) == n):
return n
else:
n -= 1
n |= n >> 1
n |= n >> 2
n |= n >> 4
n |= n >> 8
n |= n >> 16
n += 1
return (n/2)
>>> [i for i in fib_gen(11)]
def crazyFib(n):
'Crazy fast fibonacci number calculation'
powTwo = prevPowTwo(n)
q = r = i = 1
s = 0
while(i < powTwo):
i *= 2
q, r, s = q*q + r*r, r * (q + s), (r*r + s*s)
while(i < n):
i += 1
q, r, s = q+r, q, r
return q
[0,1,1,2,3,5,8,13,21,34,55]

View file

@ -1,23 +1,62 @@
/*REXX program calculates the Nth Fibonacci number, N can be zero or negative. */
numeric digits 210000 /*be able to handle ginormous numbers. */
parse arg x y . /*allow a single number or a range. */
if x=='' | x=="," then do; x=-40; y=+40; end /*No input? Then use range -40 ──► +40*/
if y=='' | y=="," then y=x /*if only one number, display fib(X).*/
w= max(length(x), length(y) ) /*W: used for making formatted output.*/
fw= 10 /*Minimum maximum width. Sounds ka─razy*/
do j=x to y; q= fib(j) /*process all of the Fibonacci requests*/
L= length(q) /*obtain the length (decimal digs) of Q*/
fw= max(fw, L) /*fib number length, or the max so far.*/
say 'Fibonacci('right(j,w)") = " right(q,fw) /*right justify Q.*/
if L>10 then say 'Fibonacci('right(j, w)") has a length of" L
end /*j*/ /* [↑] list a Fib. sequence of x──►y */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fib: procedure; parse arg n; an= abs(n) /*use │n│ (the absolute value of N).*/
a= 0; b= 1; if an<2 then return an /*handle two special cases: zero & one.*/
/* [↓] this method is non─recursive. */
do k=2 to an; $= a+b; a= b; b= $ /*sum the numbers up to │n│ */
end /*k*/ /* [↑] (only positive Fibs nums used).*/
/* [↓] an//2 [same as] (an//2==1).*/
if n>0 | an//2 then return $ /*Positive or even? Then return sum. */
return -$ /*Negative and odd? Return negative sum*/
-- 19 Sep 2025
include Setting
say 'FIBONACCI SEQUENCE'
say version
say
say 'Fibonacci numbers up to F100 are...'
call Fibonacci1 100
say
call Timer 'r'
say 'Selected Fibonacci numbers using recurrence...'
call Fibonacci2 1e2
call Fibonacci2 1e3
call Fibonacci2 1e4
call Fibonacci2 1e5
call Fibonacci2 1e6
say
call Timer 'r'
say 'Selected Fibonacci numbers using closed formula...'
call Fibonacci3 1e2
call Fibonacci3 1e3
call Fibonacci3 1e4
call Fibonacci3 1e5
say
call Timer 'r'
exit
Fibonacci1:
-- Show sequence
arg xx
numeric digits 25
call CharOut ,Right(0,22) Right(1,21)
a=0; b=1
do i=2 to xx
c=b+a; a=b; b=c
call CharOut ,Right(c,22)
if i//5=4 | i//5=9 then
say
end
say
return
Fibonacci2:
-- Get specific number sequence
arg xx
numeric digits xx/4
a=0; b=1
do i=2 to xx
f=b+a; a=b; b=f
end
say 'F'xx '=' Left(f,10)'...'Right(f,10) '('Xpon(f) 'digits)' elaps('r')'s'
return
Fibonacci3:
-- Get specific number formula
arg xx
numeric digits xx/4
f=Round(((0.5*(1+SqRt(5)))**xx-(0.5*(1-SqRt(5)))**xx)/SqRt(5))/1
say 'F'xx '=' Left(f,10)'...'Right(f,10) '('Xpon(f) 'digits)' elaps('r')'s'
return
include Math

View file

@ -1,2 +0,0 @@
F ← |1 memo⟨+⊃(F-1)(F-2)|∘⟩<2.
F ⇡20

View file

@ -1,44 +0,0 @@
class generator
dim t1
dim t2
dim tn
dim cur_overflow
Private Sub Class_Initialize
cur_overflow = false
t1 = ccur(0)
t2 = ccur(1)
tn = ccur(t1 + t2)
end sub
public default property get generated
on error resume next
generated = ccur(tn)
if err.number <> 0 then
generated = cdbl(tn)
cur_overflow = true
end if
t1 = ccur(t2)
if err.number <> 0 then
t1 = cdbl(t2)
cur_overflow = true
end if
t2 = ccur(tn)
if err.number <> 0 then
t2 = cdbl(tn)
cur_overflow = true
end if
tn = ccur(t1+ t2)
if err.number <> 0 then
tn = cdbl(t1) + cdbl(t2)
cur_overflow = true
end if
on error goto 0
end property
public property get overflow
overflow = cur_overflow
end property
end class

View file

@ -1,10 +0,0 @@
dim fib
set fib = new generator
dim i
for i = 1 to 100
wscript.stdout.write " " & fib
if fib.overflow then
wscript.echo
exit for
end if
next