Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,7 @@
---
category:
- Recursion
- Memoization
- Classic CS problems and programs
from: http://rosettacode.org/wiki/Fibonacci_sequence
note: Arithmetic operations

View file

@ -0,0 +1,33 @@
The '''Fibonacci sequence''' is a sequence &nbsp; <big> F<sub>n</sub> </big> &nbsp; of natural numbers defined recursively:
<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>
;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).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
<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.
;Related tasks:
* &nbsp; [[Fibonacci n-step number sequences]]
* &nbsp; [[Leonardo numbers]]
;References:
* &nbsp; [[wp:Fibonacci number|Wikipedia, Fibonacci number]]
* &nbsp; [[wp:Lucas number|Wikipedia, Lucas number]]
* &nbsp; [http://mathworld.wolfram.com/FibonacciNumber.html MathWorld, Fibonacci Number]
* &nbsp; [http://www.math-cs.ucmo.edu/~curtisc/articles/howardcooper/genfib4.pdf Some identities for r-Fibonacci numbers]
* &nbsp; [[oeis:A000045|OEIS Fibonacci numbers]]
* &nbsp; [[oeis:A000032|OEIS Lucas numbers]]
<br><br>

View file

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

View file

@ -0,0 +1,12 @@
F fib_iter(n)
I n < 2
R n
V fib_prev = 1
V fib = 1
L 2 .< n
(fib_prev, fib) = (fib, fib + fib_prev)
R fib
L(i) 1..20
print(fib_iter(i), end' )
print()

View file

@ -0,0 +1,51 @@
* Fibonacci sequence 05/11/2014
* integer (31 bits) = 10 decimals -> max fibo(46)
FIBONACC CSECT
USING FIBONACC,R12 base register
SAVEAREA B STM-SAVEAREA(R15) skip savearea
DC 17F'0' savearea
DC CL8'FIBONACC' eyecatcher
STM STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R12,R15 set addressability
* ----
LA R1,0 f(n-2)=0
LA R2,1 f(n-1)=1
LA R4,2 n=2
LA R6,1 step
LH R7,NN limit
LOOP EQU * for n=2 to nn
LR R3,R2 f(n)=f(n-1)
AR R3,R1 f(n)=f(n-1)+f(n-2)
CVD R4,PW n convert binary to packed (PL8)
UNPK ZW,PW packed (PL8) to zoned (ZL16)
MVC CW,ZW zoned (ZL16) to char (CL16)
OI CW+L'CW-1,X'F0' zap sign
MVC WTOBUF+5(2),CW+14 output
CVD R3,PW f(n) binary to packed decimal (PL8)
MVC ZN,EM load mask
ED ZN,PW packed dec (PL8) to char (CL20)
MVC WTOBUF+9(14),ZN+6 output
WTO MF=(E,WTOMSG) write buffer
LR R1,R2 f(n-2)=f(n-1)
LR R2,R3 f(n-1)=f(n)
BXLE R4,R6,LOOP endfor n
* ----
LM R14,R12,12(R13) restore previous savearea pointer
XR R15,R15 return code set to 0
BR R14 return to caller
* ---- DATA
NN DC H'46' nn max n
PW DS PL8 15num
ZW DS ZL16
CW DS CL16
ZN DS CL20
* ' b 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0' 15num
EM DC XL20'402020206B2020206B2020206B2020206B202120' mask
WTOMSG DS 0F
DC H'80',XL2'0000'
* fibo(46)=1836311903
WTOBUF DC CL80'fibo(12)=1234567890'
REGEQU
END FIBONACC

View file

@ -0,0 +1,48 @@
* Fibonacci sequence 31/07/2018
* packed dec (PL8) = 15 decimals => max fibo(73)
FIBOWTOP CSECT
USING FIBOWTOP,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
* ----
ZAP FNM2,=P'0' f(0)=0
ZAP FNM1,=P'1' f(1)=1
LA R4,2 n=2
LA R6,1 step
LH R7,NN limit
LOOP EQU * for n=2 to nn
ZAP FN,FNM1 f(n)=f(n-2)
AP FN,FNM2 f(n)=f(n-1)+f(n-2)
CVD R4,PW n
MVC ZN,EM load mask
ED ZN,PW packed dec (PL8) to char (CL16)
MVC WTOBUF+5(2),ZN+L'ZN-2 output
MVC ZN,EM load mask
ED ZN,FN packed dec (PL8) to char (CL16)
MVC WTOBUF+9(L'ZN),ZN output
WTO MF=(E,WTOMSG) write buffer
ZAP FNM2,FNM1 f(n-2)=f(n-1)
ZAP FNM1,FN f(n-1)=f(n)
BXLE R4,R6,LOOP endfor n
* ----
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
* ---- DATA
NN DC H'73' nn
FNM2 DS PL8 f(n-2)
FNM1 DS PL8 f(n-1)
FN DS PL8 f(n)
PW DS PL8 15num
ZN DS CL20
* ' b 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0' 15num
EM DC XL20'402020206B2020206B2020206B2020206B202120' mask
WTOMSG DS 0F
DC H'80',XL2'0000'
* fibo(73)=806515533049393
WTOBUF DC CL80'fibo(12)=123456789012345 '
REGEQU
END FIBOWTOP

View file

@ -0,0 +1,16 @@
LDA #0
STA $F0 ; LOWER NUMBER
LDA #1
STA $F1 ; HIGHER NUMBER
LDX #0
LOOP: LDA $F1
STA $0F1B,X
STA $F2 ; OLD HIGHER NUMBER
ADC $F0
STA $F1 ; NEW HIGHER NUMBER
LDA $F2
STA $F0 ; NEW LOWER NUMBER
INX
CPX #$0A ; STOP AT FIB(10)
BMI LOOP
RTS ; RETURN FROM SUBROUTINE

View file

@ -0,0 +1,20 @@
fib:
MOVEM.L D4-D5,-(SP)
MOVE.L D0,D4
MOVEQ #0,D5
CMP.L #2,D0
BCS .bar
MOVEQ #0,D5
.foo:
MOVE.L D4,D0
SUBQ.L #1,D0
JSR fib
SUBQ.L #2,D4
ADD.L D0,D5
CMP.L #1,D4
BHI .foo
.bar:
MOVE.L D5,D0
ADD.L D4,D0
MOVEM.L (SP)+,D4-D5
RTS

View file

@ -0,0 +1,10 @@
FIBNCI: MOV C, A ; C will store the counter
DCR C ; decrement, because we know f(1) already
MVI A, 1
MVI B, 0
LOOP: MOV D, A
ADD B ; A := A + B
MOV B, D
DCR C
JNZ LOOP ; jump if not zero
RET ; return from subroutine

View file

@ -0,0 +1,30 @@
fib:
; WRITTEN IN C WITH X86-64 CLANG 3.3 AND DOWNGRADED TO 16-BIT X86
; INPUT: DI = THE NUMBER YOU WISH TO CALC THE FIBONACCI NUMBER FOR.
; OUTPUTS TO AX
push BP
push BX
push AX
mov BX, DI ;COPY INPUT TO BX
xor AX, AX ;MOV AX,0
test BX, BX ;SET FLAGS ACCORDING TO BX
je LBB0_4 ;IF BX == 0 RETURN 0
cmp BX, 1 ;IF BX == 1 RETURN 1
jne LBB0_3
mov AX, 1 ;ELSE, SET AX = 1 AND RETURN
jmp LBB0_4
LBB0_3:
lea DI, WORD PTR [BX - 1] ;DI = BX - 1
call fib ;RETURN FIB(BX-1)
mov BP, AX ;STORE THIS IN BP
add BX, -2
mov DI, BX
call fib ;GET FIB(DI - 2)
add AX, BP ;RETURN FIB(DI - 1) + FIB(DI - 2)
LBB0_4:
add sp,2
pop BX
pop BP
ret

View file

@ -0,0 +1,31 @@
getfib:
;input: BX = the desired fibonacci number (in other words, the "n" in "F(n)")
; DS must point to the segment where the fibonacci table is stored
;outputs to DX:AX (DX = high word, AX = low word)
push ds
cmp bx,41 ;bounds check
ja IndexOutOfBounds
shl bx,1
shl bx,1 ;multiply by 4, since this is a table of dwords
mov ax,@code
mov ds,ax
mov si,offset fib
mov ax,[ds:si] ;fetch the low word into AX
mov dx,2[ds:si] ;fetch the high word into DX
pop ds
ret
IndexOutOfBounds:
stc ;set carry to indicate an error
mov ax,0FFFFh ;return FFFF as the error code
pop ds
ret
;table of the first 41 fibonacci numbers
fib dword 0, 1, 1, 2, 3, 5, 8, 13
dword 21, 34, 55, 89, 144, 233, 377, 610
dword 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657
dword 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269
dword 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986
dword 102334155

View file

@ -0,0 +1,8 @@
: fibon \ n -- fib(n)
>r 0 1
( tuck n:+ ) \ fib(n-2) fib(n-1) -- fib(n-1) fib(n)
r> n:1- times ;
: fib \ n -- fib(n)
dup 1 n:= if 1 ;; then
fibon nip ;

View file

@ -0,0 +1,14 @@
FORM fibonacci_iter USING index TYPE i
CHANGING number_fib TYPE i.
DATA: lv_old type i,
lv_cur type i.
Do index times.
If sy-index = 1 or sy-index = 2.
lv_cur = 1.
lv_old = 0.
endif.
number_fib = lv_cur + lv_old.
lv_old = lv_cur.
lv_cur = number_fib.
enddo.
ENDFORM.

View file

@ -0,0 +1,9 @@
cl_demo_output=>display( REDUCE #( INIT fibnm = VALUE stringtab( ( |0| ) ( |1| ) )
n TYPE string
x = `0`
y = `1`
FOR i = 1 WHILE i <= 100
NEXT n = ( x + y )
fibnm = VALUE #( BASE fibnm ( n ) )
x = y
y = n ) ).

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,19 @@
begin
comment Fibonacci sequence;
integer procedure fibonacci(n); value n; integer n;
begin
integer i, fn, fn1, fn2;
fn2 := 1;
fn1 := 0;
fn := 0;
for i := 1 step 1 until n do begin
fn := fn1 + fn2;
fn2 := fn1;
fn1 := fn
end;
fibonacci := fn
end fibonacci;
integer i;
for i := 0 step 1 until 20 do outinteger(1,fibonacci(i))
end

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,13 @@
INTEGER FUNCTION FIBONACCI( X ); INTEGER X;
BEGIN
INTEGER M, N, A, I;
M := 0;
N := 1;
FOR I := 2 STEP 1 UNTIL X DO
BEGIN
A := N;
N := M + N;
M := A;
END;
FIBONACCI := N;
END;

View file

@ -0,0 +1,7 @@
INTEGER FUNCTION FIBONACCI( X ); INTEGER X;
BEGIN
IF X < 3 THEN
FIBONACCI := 1
ELSE
FIBONACCI := FIBONACCI( X - 2 ) + FIBONACCI( X - 1 );
END;

View file

@ -0,0 +1,19 @@
begin
% return the nth Fibonacci number %
integer procedure Fibonacci( integer value n ) ;
begin
integer fn, fn1, fn2;
fn2 := 1;
fn1 := 0;
fn := 0;
for i := 1 until n do begin
fn := fn1 + fn2;
fn2 := fn1;
fn1 := fn
end ;
fn
end Fibonacci ;
for i := 0 until 10 do writeon( i_w := 3, s_w := 0, Fibonacci( i ) )
end.

View file

@ -0,0 +1,4 @@
/Sequence
fib:{<0;1> {x,<x[-1]+x[-2]>}/ range[x]}
/nth
fibn:{fib[x][x]}

View file

@ -0,0 +1 @@
fib{1: ( -1)+ -2}

View file

@ -0,0 +1 @@
+.×/N/2 21 1 1 0

View file

@ -0,0 +1 @@
0 1+.×/N/2 21 1 1 0

View file

@ -0,0 +1 @@
.5+(((1+PHI)÷2)*N)÷PHI5*.5

View file

@ -0,0 +1,16 @@
fibonacci:
push {r1-r3}
mov r1, #0
mov r2, #1
fibloop:
mov r3, r2
add r2, r1, r2
mov r1, r3
sub r0, r0, #1
cmp r0, #1
bne fibloop
mov r0, r2
pop {r1-r3}
mov pc, lr

View file

@ -0,0 +1,2 @@
fun fib_rec(n: int): int =
if n >= 2 then fib_rec(n-1) + fib_rec(n-2) else n

View file

@ -0,0 +1,9 @@
(*
** This one is also referred to as being tail-recursive
*)
fun
fib_trec(n: int): int =
if
n > 0
then (fix loop (i:int, r0:int, r1:int): int => if i > 1 then loop (i-1, r1, r0+r1) else r1)(n, 0, 1)
else 0

View file

@ -0,0 +1,27 @@
(*
** This implementation is verified!
*)
dataprop FIB (int, int) =
| FIB0 (0, 0) | FIB1 (1, 1)
| {n:nat} {r0,r1:int} FIB2 (n+2, r0+r1) of (FIB (n, r0), FIB (n+1, r1))
// end of [FIB] // end of [dataprop]
fun
fibats{n:nat}
(n: int (n))
: [r:int] (FIB (n, r) | int r) = let
fun loop
{i:nat | i <= n}{r0,r1:int}
(
pf0: FIB (i, r0), pf1: FIB (i+1, r1)
| ni: int (n-i), r0: int r0, r1: int r1
) : [r:int] (FIB (n, r) | int r) =
if (ni > 0)
then loop{i+1}(pf1, FIB2 (pf0, pf1) | ni - 1, r1, r0 + r1)
else (pf0 | r0)
// end of [if]
// end of [loop]
in
loop {0} (FIB0 (), FIB1 () | n, 0, 1)
end // end of [fibats]

View file

@ -0,0 +1,79 @@
(* ****** ****** *)
//
// How to compile:
// patscc -o fib fib.dats
//
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
//
abst@ype
int3_t0ype =
(int, int, int)
//
typedef int3 = int3_t0ype
//
(* ****** ****** *)
extern
fun int3 : (int, int, int) -<> int3
extern
fun int3_1 : int3 -<> int
extern
fun mul_int3_int3: (int3, int3) -<> int3
(* ****** ****** *)
local
assume
int3_t0ype = (int, int, int)
in (* in-of-local *)
//
implement
int3 (x, y, z) = @(x, y, z)
//
implement int3_1 (xyz) = xyz.1
//
implement
mul_int3_int3
(
@(a,b,c), @(d,e,f)
) =
(a*d + b*e, a*e + b*f, b*e + c*f)
//
end // end of [local]
(* ****** ****** *)
//
implement
gnumber_int<int3> (n) = int3(n, 0, n)
//
implement gmul_val<int3> = mul_int3_int3
//
(* ****** ****** *)
//
fun
fib (n: intGte(0)): int =
int3_1(gpow_int_val<int3> (n, int3(1, 1, 0)))
//
(* ****** ****** *)
implement
main0 () =
{
//
val N = 10
val () = println! ("fib(", N, ") = ", fib(N))
val N = 20
val () = println! ("fib(", N, ") = ", fib(N))
val N = 30
val () = println! ("fib(", N, ") = ", fib(N))
val N = 40
val () = println! ("fib(", N, ") = ", fib(N))
//
} (* end of [main0] *)

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,48 @@
INT FUNC Fibonacci(INT n)
INT curr,prev,tmp
IF n>=-1 AND n<=1 THEN
RETURN (n)
FI
prev=0
IF n>0 THEN
curr=1
DO
tmp=prev
prev=curr
curr==+tmp
n==-1
UNTIL n=1
OD
ELSE
curr=-1
DO
tmp=prev
prev=curr
curr==+tmp
n==+1
UNTIL n=-1
OD
FI
RETURN (curr)
PROC Main()
BYTE n
INT f
Put(125) ;clear screen
FOR n=0 TO 22
DO
f=Fibonacci(n)
Position(2,n+1)
PrintF("Fib(%I)=%I",n,f)
IF n>0 THEN
f=Fibonacci(-n)
Position(21,n+1)
PrintF("Fib(%I)=%I",-n,f)
FI
OD
RETURN

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,49 @@
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

@ -0,0 +1,10 @@
module FibonacciSequence where
open import Data.Nat using ( ; zero ; suc ; _+_)
rec_fib : (m : ) -> (a : ) -> (b : ) ->
rec_fib zero a b = a
rec_fib (suc k) a b = rec_fib k b (a + b)
fib : (n : ) ->
fib n = rec_fib n zero (suc zero)

View file

@ -0,0 +1,25 @@
integer
fibs(integer n)
{
integer w;
if (n == 0) {
w = 0;
} elif (n == 1) {
w = 1;
} else {
integer a, b, i;
i = 1;
a = 0;
b = 1;
while (i < n) {
w = a + b;
a = b;
b = w;
i += 1;
}
}
return w;
}

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,42 @@
#include <hbasic.h>
#define TERM1 1.61803398874989
#define TERM2 -0.61803398874989
#context get Fibonacci number with analitic mode
GetArgs(n)
get Inv of (M_SQRT5), Mul by( Pow (TERM 1, n), Minus( Pow(TERM 2, n) ) );
then Return\\
#proto fibonacci_recursive(__X__)
#synon _fibonacci_recursive getFibonaccinumberwithrecursivemodeof
#proto fibonacci_iterative(__X__)
#synon _fibonacci_iterative getFibonaccinumberwithiterativemodeof
Begin
Option Stack 1024
get Arg Number(2, n), and Take( n );
then, get Fibonacci number with analitic mode, and Print It with a Newl.
secondly, get Fibonacci number with recursive mode of(n), and Print It with a Newl.
finally, get Fibonacci number with iterative mode of (n), and Print It with a Newl.
End
Subrutines
fibonacci_recursive(n)
Iif ( var(n) Is Le? (2), 1 , \
get Fibonacci number with recursive mode of( var(n) Minus (1));\
get Fibonacci number with recursive mode of( var(n) Minus (2)); and Add It )
Return
fibonacci_iterative(n)
A=0
B=1
For Up( I:=2, n, 1 )
C=B
Let ( B: = var(A) Plus (B) )
A=C
Next
Return(B)

View file

@ -0,0 +1,43 @@
/*
author: snugsfbay
date: March 3, 2016
description: Create a list of x numbers in the Fibonacci sequence.
- user may specify the length of the list
- enforces a minimum of 2 numbers in the sequence because any fewer is not a sequence
- enforces a maximum of 47 because further values are too large for integer data type
- Fibonacci sequence always starts with 0 and 1 by definition
*/
public class FibNumbers{
final static Integer MIN = 2; //minimum length of sequence
final static Integer MAX = 47; //maximum length of sequence
/*
description: method to create a list of numbers in the Fibonacci sequence
param: user specified integer representing length of sequence should be 2-47, inclusive.
- Sequence starts with 0 and 1 by definition so the minimum length could be as low as 2.
- For 48th number in sequence or greater, code would require a Long data type rather than an Integer.
return: list of integers in sequence.
*/
public static List<Integer> makeSeq(Integer len){
List<Integer> fib = new List<Integer>{0,1}; // initialize list with first two values
Integer i;
if(len<MIN || len==null || len>MAX) {
if (len>MAX){
len=MAX; //set length to maximum if user entered too high a value
}else{
len=MIN; //set length to minimum if user entered too low a value or none
}
} //This could be refactored using teneray operator, but we want code coverage to be reflected for each condition
//start with initial list size to find previous two values in the sequence, continue incrementing until list reaches user defined length
for(i=fib.size(); i<len; i++){
fib.add(fib[i-1]+fib[i-2]); //create new number based on previous numbers and add that to the list
}
return fib;
}
}

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,9 @@
on fib(n)
if n < 1 then
0
else if n < 3 then
1
else
fib(n - 2) + fib(n - 1)
end if
end fib

View file

@ -0,0 +1,62 @@
-------------------- FIBONACCI SEQUENCE --------------------
-- fib :: Int -> Int
on fib(n)
-- lastTwo : (Int, Int) -> (Int, Int)
script lastTwo
on |λ|([a, b])
[b, a + b]
end |λ|
end script
item 1 of foldl(lastTwo, {0, 1}, enumFromTo(1, n))
end fib
--------------------------- TEST ---------------------------
on run
fib(32)
--> 2178309
end run
-------------------- GENERIC FUNCTIONS ---------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
lst
else
{}
end if
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn

View file

@ -0,0 +1,31 @@
IT'S SHOWTIME
HEY CHRISTMAS TREE f1
YOU SET US UP @I LIED
TALK TO THE HAND f1
HEY CHRISTMAS TREE f2
YOU SET US UP @NO PROBLEMO
HEY CHRISTMAS TREE f3
YOU SET US UP @I LIED
STICK AROUND @NO PROBLEMO
GET TO THE CHOPPER f3
HERE IS MY INVITATION f1
GET UP f2
ENOUGH TALK
TALK TO THE HAND f3
GET TO THE CHOPPER f1
HERE IS MY INVITATION f2
ENOUGH TALK
GET TO THE CHOPPER f2
HERE IS MY INVITATION f3
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED

View file

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

@ -0,0 +1,9 @@
/--#$--\
| |
>-*>{+}/
| \+-/
1 |
# 1
| #
| |
. .

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,11 @@
Lbl FIB
r₁→N
0→I
1→J
For(K,1,N)
I+J→T
J→I
T→J
End
J
Return

View file

@ -0,0 +1,24 @@
# Basic-256 ver 1.1.4
# iterative Fibonacci sequence
# Matches sequence A000045 in the OEIS, https://oeis.org/A000045/list
# Return the Nth Fibonacci number
input "N = ",f
limit = 500 # set upper limit - can be changed, removed
f = int(f)
if f > limit then f = limit
a = 0 : b = 1 : c = 0 : n = 0 # initial values
while n < f
print n + chr(9) + c # chr(9) = tab
a = b
b = c
c = a + b
n += 1
end while
print " "
print n + chr(9) + c

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,15 @@
get "libhdr"
let fib(n) = n<=1 -> n, valof
$( let a=0 and b=1
for i=2 to n
$( let c=a
a := b
b := a+c
$)
resultis b
$)
let start() be
for i=0 to 10 do
writef("F_%N*T= %N*N", i, fib(i))

View file

@ -0,0 +1 @@
Fib {𝕩>1 ? (𝕊 𝕩-1) + 𝕊 𝕩-2; 𝕩}

View file

@ -0,0 +1 @@
Fib2 {(𝕩-1) (𝕩>1)𝕩, +𝕊 𝕩-2}

View file

@ -0,0 +1 @@
{(+`)𝕩 01}

View file

@ -0,0 +1 @@
fib { <- 0 1 { dup <- + -> swap } -> times zap } <

View file

@ -0,0 +1 @@
{19 iter - fib !} 20 times collect ! lsnum !

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,43 @@
// Fibonacci sequence, recursive version
fun fibb
loop
a = funparam[0]
break (a < 2)
a--
// Save "a" while calling fibb
a -> stack
// Set the parameter and call fibb
funparam[0] = a
call fibb
// Handle the return value and restore "a"
b = funparam[0]
stack -> a
// Save "b" while calling fibb again
b -> stack
a--
// Set the parameter and call fibb
funparam[0] = a
call fibb
// Handle the return value and restore "b"
c = funparam[0]
stack -> b
// Sum the results
b += c
a = b
funparam[0] = a
break
end
end
// vim: set syntax=c ts=4 sw=4 et:

View file

@ -0,0 +1,15 @@
#! /usr/bin/bc -q
define fib(x) {
if (x <= 0) return 0;
if (x == 1) return 1;
a = 0;
b = 1;
for (i = 1; i < x; i++) {
c = a+b; a = b; b = c;
}
return c;
}
fib(1000)
quit

View file

@ -0,0 +1,4 @@
#>'#{;
_`Enter n: `TN`Fib(`{`)=`X~P~K#{;
#>~P~L#MM@>+@'q@{;
b~@M<

View file

@ -0,0 +1,29 @@
julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i0
Fib(0)=0
Program finished!
julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i10
Fib(10)=55
Program finished!
julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i92
Fib(92)=7540113804746346429
Program finished!
julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i93
Fib(93)=12200160415121876738
Program finished!
julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i94
Fib(94)=1293530146158671551
Program finished!

View file

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

View file

@ -0,0 +1,18 @@
local a:int = 0, b:int = 1, c:int = 1, n:int
n = int(input( "Enter n: "))
if n = 0 then
print 0
end
else if n = 1
print 1
end
end if
while n>2
a = b
b = c
c = a + b
n = n - 1
wend
print c

View file

@ -0,0 +1,4 @@
: fib ( nth:ecx -- result:edi ) 1 0
: compute ( times:ecx accum:eax scratch:edi -- result:edi ) xadd latest loop ;
: example ( -- ) 11 fib drop ;

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 @@
0 1{{.+}c!}{1000.<}w!

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 @@
public static ulong Fib(uint n) {
return (n < 2)? n : Fib(n - 1) + Fib(n - 2);
}

View file

@ -0,0 +1,6 @@
public static ulong Fib(uint n) {
var M = new Matrix(1,0,0,1);
var N = new Matrix(1,1,1,0);
for (uint i = 1; i < n; i++) M *= N;
return (ulong)M[0][0];
}

View file

@ -0,0 +1,16 @@
private static Matrix M;
private static readonly Matrix N = new Matrix(1,1,1,0);
public static ulong Fib(uint n) {
M = new Matrix(1,0,0,1);
MatrixPow(n-1);
return (ulong)M[0][0];
}
private static void MatrixPow(double n){
if (n > 1) {
MatrixPow(n/2);
M *= M;
}
if (n % 2 == 0) M *= N;
}

View file

@ -0,0 +1,17 @@
private static int[] fibs = new 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};
public static int Fib(int n) {
if(n < -46 || n > 46) throw new ArgumentOutOfRangeException("n", n, "Has to be between -46 and 47.")
return fibs[n+46];
}

View file

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program
{
// A sparse array of values calculated along the way
static SortedList<int, BI> sl = new SortedList<int, BI>();
// This routine is semi-recursive, but doesn't need to evaluate every number up to n.
// Algorithm from here: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html#section3
static BI Fsl(int n)
{
if (n < 2) return n;
int n2 = n >> 1, pm = n2 + ((n & 1) << 1) - 1; IfNec(n2); IfNec(pm);
return n2 > pm ? (2 * sl[pm] + sl[n2]) * sl[n2] : sqr(sl[n2]) + sqr(sl[pm]);
// Helper routine for Fsl(). It adds an entry to the sorted list when necessary
void IfNec(int x) { if (!sl.ContainsKey(x)) sl.Add(x, Fsl(x)); }
// Helper function to square a BigInteger
BI sqr(BI x) { return x * x; }
}
// Conventional iteration method (not used here)
public static BI Fm(BI n)
{
if (n < 2) return n; BI cur = 0, pre = 1;
for (int i = 0; i <= n - 1; i++) { BI sum = cur + pre; pre = cur; cur = sum; }
return cur;
}
public static void Main()
{
int num = 2_000_000, digs = 35, vlen;
var sw = System.Diagnostics.Stopwatch.StartNew(); var v = Fsl(num); sw.Stop();
Console.Write("{0:n3} ms to calculate the {1:n0}th Fibonacci number, ",
sw.Elapsed.TotalMilliseconds, num);
Console.WriteLine("number of digits is {0}", vlen = (int)Math.Ceiling(BI.Log10(v)));
if (vlen < 10000) {
sw.Restart(); Console.WriteLine(v); sw.Stop();
Console.WriteLine("{0:n3} ms to write it to the console.", sw.Elapsed.TotalMilliseconds);
} else
Console.Write("partial: {0}...{1}", v / BI.Pow(10, vlen - digs), v % BI.Pow(10, digs));
}
}

View file

@ -0,0 +1,29 @@
using System;
using BI = System.Numerics.BigInteger;
class Program {
// returns the nth Fibonacci number without calculating 0..n-1
static BI oneFib(int n) {
BI z = (BI)1 << ++n;
return BI.ModPow(z, n, (z << n) - z - 1) % z;
}
// returns an array of Fibonacci numbers from the 0th to the nth
static BI[] fibTab(int n) {
var res = new BI[++n];
BI z = (BI)1 << 1, zz = z << 1;
for (int i = 0; i < n; ) {
res[i] = BI.ModPow(z, ++i, zz - z - 1) % z;
z <<= 1; zz <<= 2;
}
return res;
}
static void Main(string[] args) {
int n = 20;
Console.WriteLine("Fibonacci numbers 0..{0}: {1}", n, string.Join(" ",fibTab(n)));
n = 1000;
Console.WriteLine("Fibonacci({0}): {1}", n, oneFib(n));
}
}

View file

@ -0,0 +1,7 @@
public static ulong Fib(uint n) {
return Fib(0, 1, n);
}
private static ulong Fib(ulong a, ulong b, uint n) {
return (n < 1)? a :(n == 1)? b : Fib(b, a + b, n - 1);
}

View file

@ -0,0 +1,13 @@
public static ulong Fib(uint x) {
if (x == 0) return 0;
ulong prev = 0;
ulong next = 1;
for (int i = 1; i < x; i++)
{
ulong sum = prev + next;
prev = next;
next = sum;
}
return next;
}

View file

@ -0,0 +1,11 @@
using System; using System.Text; // FIBRUS.cs Russia
namespace Fibrus { class Program { static void Main()
{ long fi1=1; long fi2=1; long fi3=1; int da; int i; int d;
for (da=1; da<=78; da++) // rextester.com/MNGUV70257
{ d = 20-Convert.ToInt32((Convert.ToString(fi3)).Length);
for (i=1; i<d; i++) Console.Write(".");
Console.Write(fi3); Console.Write(" "); Console.WriteLine(da);
fi3 = fi2 + fi1;
fi1 = fi2;
fi2 = fi3;
}}}}

View file

@ -0,0 +1,14 @@
public static IEnumerable<long> Fibs(uint x) {
IList<ulong> fibs = new List<ulong>();
ulong prev = -1;
ulong next = 1;
for (int i = 0; i < x; i++)
{
long sum = prev + next;
prev = next;
next = sum;
fibs.Add(sum);
}
return fibs;
}

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