Data update

This commit is contained in:
Ingy döt Net 2026-04-30 12:34:36 -04:00
parent 4bb20c9b71
commit cbaf4c4b64
12390 changed files with 318560 additions and 27248 deletions

View file

@ -1,20 +1,20 @@
fib:
MOVEM.L D4-D5,-(SP)
MOVE.L D0,D4
MOVEQ #0,D5
CMP.L #2,D0
BCS .bar
MOVEQ #0,D5
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
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
MOVE.L D5,D0
ADD.L D4,D0
MOVEM.L (SP)+,D4-D5
RTS

View file

@ -1,100 +1,100 @@
;-------------------------------------------------------
; useful equates
;-------------------------------------------------------
bdos equ 5 ; BDOS entry
cr equ 13 ; ASCII carriage return
lf equ 10 ; ASCII line feed
space equ 32 ; ASCII space char
conout equ 2 ; BDOS console output function
putstr equ 9 ; BDOS print string function
nterms equ 20 ; number of terms (max=24) to display
;-------------------------------------------------------
; main code begins here
;-------------------------------------------------------
org 100h
lxi h,0 ; save CP/M's stack
dad sp
shld oldstk
lxi sp,stack ; set our own stack
lxi d,signon ; print signon message
mvi c,putstr
call bdos
mvi a,0 ; start with Fib(0)
mloop: push a ; save our count
call fib
call putdec
mvi a,space ; separate the numbers
call putchr
pop a ; get our count back
inr a ; increment it
cpi nterms+1 ; have we reached our limit?
jnz mloop ; no, keep going
lhld oldstk ; all done; get CP/M's stack back
sphl ; restore it
ret ; back to command processor
;-------------------------------------------------------
; calculate nth Fibonacci number (max n = 24)
; entry: A = n
; exit: HL = Fib(n)
;-------------------------------------------------------
fib: mov c,a ; C holds n
lxi d,0 ; DE holds Fib(n-2)
lxi h,1 ; HL holds Fib(n-1)
ana a ; Fib(0) is a special case
jnz fib2 ; n > 0 so calculate normally
xchg ; otherwise return with HL=0
ret
fib2: dcr c
jz fib3 ; we're done
push h ; save Fib(n-1)
dad d ; HL = Fib(n), soon to be Fib(n-1)
pop d ; DE = old F(n-1), now Fib(n-2)
jmp fib2 ; ready for next pass
fib3: ret
;-------------------------------------------------------
; console output of char in A register
;-------------------------------------------------------
putchr: push h
push d
push b
mov e,a
mvi c,conout
call bdos
pop b
pop d
pop h
ret
;---------------------------------------------------------
; Output decimal number to console
; HL holds 16-bit unsigned binary number to print
;---------------------------------------------------------
putdec: push b
push d
push h
lxi b,-10
lxi d,-1
;-------------------------------------------------------
; useful equates
;-------------------------------------------------------
bdos equ 5 ; BDOS entry
cr equ 13 ; ASCII carriage return
lf equ 10 ; ASCII line feed
space equ 32 ; ASCII space char
conout equ 2 ; BDOS console output function
putstr equ 9 ; BDOS print string function
nterms equ 20 ; number of terms (max=24) to display
;-------------------------------------------------------
; main code begins here
;-------------------------------------------------------
org 100h
lxi h,0 ; save CP/M's stack
dad sp
shld oldstk
lxi sp,stack ; set our own stack
lxi d,signon ; print signon message
mvi c,putstr
call bdos
mvi a,0 ; start with Fib(0)
mloop: push a ; save our count
call fib
call putdec
mvi a,space ; separate the numbers
call putchr
pop a ; get our count back
inr a ; increment it
cpi nterms+1 ; have we reached our limit?
jnz mloop ; no, keep going
lhld oldstk ; all done; get CP/M's stack back
sphl ; restore it
ret ; back to command processor
;-------------------------------------------------------
; calculate nth Fibonacci number (max n = 24)
; entry: A = n
; exit: HL = Fib(n)
;-------------------------------------------------------
fib: mov c,a ; C holds n
lxi d,0 ; DE holds Fib(n-2)
lxi h,1 ; HL holds Fib(n-1)
ana a ; Fib(0) is a special case
jnz fib2 ; n > 0 so calculate normally
xchg ; otherwise return with HL=0
ret
fib2: dcr c
jz fib3 ; we're done
push h ; save Fib(n-1)
dad d ; HL = Fib(n), soon to be Fib(n-1)
pop d ; DE = old F(n-1), now Fib(n-2)
jmp fib2 ; ready for next pass
fib3: ret
;-------------------------------------------------------
; console output of char in A register
;-------------------------------------------------------
putchr: push h
push d
push b
mov e,a
mvi c,conout
call bdos
pop b
pop d
pop h
ret
;---------------------------------------------------------
; Output decimal number to console
; HL holds 16-bit unsigned binary number to print
;---------------------------------------------------------
putdec: push b
push d
push h
lxi b,-10
lxi d,-1
putdec2:
dad b
inx d
jc putdec2
lxi b,10
dad b
xchg
mov a,h
ora l
cnz putdec ; recursive call
mov a,e
adi '0'
call putchr
pop h
pop d
pop b
ret
;-------------------------------------------------------
; data area
;-------------------------------------------------------
signon: db 'Fibonacci number sequence:',cr,lf,'$'
oldstk: dw 0
stack equ $+128 ; 64-level stack
;
end
dad b
inx d
jc putdec2
lxi b,10
dad b
xchg
mov a,h
ora l
cnz putdec ; recursive call
mov a,e
adi '0'
call putchr
pop h
pop d
pop b
ret
;-------------------------------------------------------
; data area
;-------------------------------------------------------
signon: db 'Fibonacci number sequence:',cr,lf,'$'
oldstk: dw 0
stack equ $+128 ; 64-level stack
;
end

View file

@ -1,30 +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
; 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
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
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
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)
mov DI, BX
call fib ;GET FIB(DI - 2)
add AX, BP ;RETURN FIB(DI - 1) + FIB(DI - 2)
LBB0_4:
add sp,2
add sp,2
pop BX
pop BP
ret

View file

@ -0,0 +1,22 @@
100 REM Fibonacci sequence
110 DECLARE EXTERNAL FUNCTION Fib
120 INPUT PROMPT "Enter n for fib(n): ": N
130 PRINT Fib(N)
140 END
150 REM ***
160 EXTERNAL FUNCTION Fib(N)
170 IF N = 0 THEN
180 LET Fib = 0
190 ELSEIF N = 1 THEN
200 LET Fib = 1
210 ELSE
220 LET Prev = 0
230 LET Curr = 1
240 FOR I = 2 TO N
250 LET T = Curr
260 LET Curr = Prev + Curr
270 LET Prev = T
280 NEXT I
290 LET Fib = Curr
300 END IF
310 END FUNCTION

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

@ -2,10 +2,10 @@ 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
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,2 @@
0 DEF FN F(N) = INT ((((1 + SQR (5)) / 2) ^ N - ((1 - SQR (5)) / 2) ^ N) / SQR (5) + 0.5)
1 S = - 38: FOR I = S TO - S: PRINT MID$ (" ",(I = S) + 1) FN F(I);: NEXT

View file

@ -0,0 +1 @@
? FN F(39)" " FN F(45)" " FN F(183)

View file

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

View file

@ -0,0 +1,18 @@
fib: function [n][
if n < 2 -> return 1
a: 1
b: 1
loop 2..n 'x [
tmp: a + b
a: b
b: tmp
]
return b
]
loop 1..25 'x [
print ["Fibonacci of" x "=" fib x]
]

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,22 @@
// https://rosettacode.org/wiki/Fibonacci_sequence
import ballerina/io;
function fib_iter(int n) returns int {
if (n < 2) {
return n;
}
int fib_prev = 1;
int fib = 1;
int temp = 0;
foreach int _ in int:range(2, n, 1) {
temp = fib;
fib = fib_prev + fib;
fib_prev = temp;
}
return fib;
}
public function main() {
foreach int i in int:range(1, 21, 1) {
io:println(fib_iter(i));
}
}

View file

@ -1,2 +1,16 @@
++++++++++
>>+<<[->[->+>+<<]>[-<+>]>[-<+>]<<<]
Print the number
>>[-]<[->+<]>
>+
[[-]<
[->+<
[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<
[->[-]>>+>+<<<]
]]]]]]]]<
]>>[>]++++++[-<++++++++>]>>
]<<<[.[-]<<<]
<+++++++++++++.---.

View file

@ -1,37 +1,37 @@
+++++ +++++ #0 set to n
>> + Init #2 to 1
+++++ +++++ #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
]
- #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
<<<< 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
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

@ -9,12 +9,12 @@ fib-unary [0 [[[2 0 [2 (1 0)]]]] k i]
# ternary fibonacci using infinite list iteration (very fast)
fib-list \index fibs
fibs head <$> (iterate &[[0 : (1 + 0)]] ((+0) : (+1)))
fibs head <$> (iterate &[[0 : (1 + 0)]] ((+0) : (+1)))
:test (fib-list (+6)) ((+8))
# recursive fib (very slow)
fib-rec y [[0 <? (+1) (+0) (0 <? (+2) (+1) rec)]]
rec (1 --0) + (1 --(--0))
rec (1 --0) + (1 --(--0))
:test (fib-rec (+6)) ((+8))

View file

@ -1,9 +1,9 @@
long long int fibb(int n) {
int fnow = 0, fnext = 1, tempf;
while(--n>0){
tempf = fnow + fnext;
fnow = fnext;
fnext = tempf;
}
return fnext;
int fnow = 0, fnext = 1, tempf;
while(--n>0){
tempf = fnow + fnext;
fnow = fnext;
fnext = tempf;
}
return fnext;
}

View file

@ -4,9 +4,9 @@
typedef struct node node;
struct node {
int n;
mpz_t v;
node *next;
int n;
mpz_t v;
node *next;
};
#define CSIZE 37
@ -15,60 +15,60 @@ node *cache[CSIZE];
// very primitive linked hash table
node * find_cache(int n)
{
int idx = n % CSIZE;
node *p;
int idx = n % CSIZE;
node *p;
for (p = cache[idx]; p && p->n != n; p = p->next);
if (p) return p;
for (p = cache[idx]; p && p->n != n; p = p->next);
if (p) return p;
p = malloc(sizeof(node));
p->next = cache[idx];
cache[idx] = p;
p = malloc(sizeof(node));
p->next = cache[idx];
cache[idx] = p;
if (n < 2) {
p->n = n;
mpz_init_set_ui(p->v, 1);
} else {
p->n = -1; // -1: value not computed yet
mpz_init(p->v);
}
return p;
if (n < 2) {
p->n = n;
mpz_init_set_ui(p->v, 1);
} else {
p->n = -1; // -1: value not computed yet
mpz_init(p->v);
}
return p;
}
mpz_t tmp1, tmp2;
mpz_t *fib(int n)
{
int x;
node *p = find_cache(n);
int x;
node *p = find_cache(n);
if (p->n < 0) {
p->n = n;
x = n / 2;
if (p->n < 0) {
p->n = n;
x = n / 2;
mpz_mul(tmp1, *fib(x-1), *fib(n - x - 1));
mpz_mul(tmp2, *fib(x), *fib(n - x));
mpz_add(p->v, tmp1, tmp2);
}
return &p->v;
mpz_mul(tmp1, *fib(x-1), *fib(n - x - 1));
mpz_mul(tmp2, *fib(x), *fib(n - x));
mpz_add(p->v, tmp1, tmp2);
}
return &p->v;
}
int main(int argc, char **argv)
{
int i, n;
if (argc < 2) return 1;
int i, n;
if (argc < 2) return 1;
mpz_init(tmp1);
mpz_init(tmp2);
mpz_init(tmp1);
mpz_init(tmp2);
for (i = 1; i < argc; i++) {
n = atoi(argv[i]);
if (n < 0) {
printf("bad input: %s\n", argv[i]);
continue;
}
for (i = 1; i < argc; i++) {
n = atoi(argv[i]);
if (n < 0) {
printf("bad input: %s\n", argv[i]);
continue;
}
// about 75% of time is spent in printing
gmp_printf("%Zd\n", *fib(n));
}
return 0;
// about 75% of time is spent in printing
gmp_printf("%Zd\n", *fib(n));
}
return 0;
}

View file

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

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

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

View file

@ -1,7 +1,7 @@
(defun fibonacci (n)
(let ((a 0) (b 1) (c n))
(loop for i from 2 to n do
(setq c (+ a b)
a b
b c))
(setq c (+ a b)
a b
b c))
c))

View file

@ -5,10 +5,10 @@ print "Fibonacci Sequence"
for i = 0 to 20
let s = a + b
let a = b
let b = s
let s = a + b
let a = b
let b = s
print s
print s
next i

View file

@ -1,7 +1,7 @@
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;
@ -9,12 +9,12 @@ function fib(n: Int64): Int64;
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];
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
@ -24,7 +24,7 @@ function fib(n: Int64): Int64;
var
matrix: TFibMat;
begin
matrix[0,0] := 1;
matrix[0,1] := 1;

View file

@ -2,12 +2,12 @@
FibFunction(UNSIGNED2 n) := FUNCTION
REAL Sqrt5 := Sqrt(5);
REAL Phi := (1+Sqrt(5))/2;
REAL Phi_Inv := 1/Phi;
UNSIGNED FibValue := ROUND( ( POWER(Phi,n)-POWER(Phi_Inv,n) ) /Sqrt5);
RETURN FibValue;
END;
REAL Sqrt5 := Sqrt(5);
REAL Phi := (1+Sqrt(5))/2;
REAL Phi_Inv := 1/Phi;
UNSIGNED FibValue := ROUND( ( POWER(Phi,n)-POWER(Phi_Inv,n) ) /Sqrt5);
RETURN FibValue;
END;
FibSeries(UNSIGNED2 n) := FUNCTION

View file

@ -1,50 +1,50 @@
class
APPLICATION
APPLICATION
create
make
make
feature
fibonacci (n: INTEGER): INTEGER
require
non_negative: n >= 0
local
i, n2, n1, tmp: INTEGER
do
n2 := 0
n1 := 1
from
i := 1
until
i >= n
loop
tmp := n1
n1 := n2 + n1
n2 := tmp
i := i + 1
end
Result := n1
if n = 0 then
Result := 0
end
end
fibonacci (n: INTEGER): INTEGER
require
non_negative: n >= 0
local
i, n2, n1, tmp: INTEGER
do
n2 := 0
n1 := 1
from
i := 1
until
i >= n
loop
tmp := n1
n1 := n2 + n1
n2 := tmp
i := i + 1
end
Result := n1
if n = 0 then
Result := 0
end
end
feature {NONE} -- Initialization
make
-- Run application.
do
print (fibonacci (0))
print (" ")
print (fibonacci (1))
print (" ")
print (fibonacci (2))
print (" ")
print (fibonacci (3))
print (" ")
print (fibonacci (4))
print ("%N")
end
make
-- Run application.
do
print (fibonacci (0))
print (" ")
print (fibonacci (1))
print (" ")
print (fibonacci (2))
print (" ")
print (fibonacci (3))
print (" ")
print (fibonacci (4))
print ("%N")
end
end

View file

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

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

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

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

@ -6,12 +6,12 @@ print "Fibonacci Sequence"
do
let s = a + b
let a = b
let b = s
+1 i
let s = a + b
let a = b
let b = s
+1 i
print s
print s
loop i < 20

View file

@ -1,40 +1,40 @@
type
/// domain for Fibonacci function
/// where result is within nativeUInt
// You can not name it fibonacciDomain,
// since the Fibonacci function itself
// is defined for all whole numbers
// but the result beyond F(n) exceeds high(nativeUInt).
fibonacciLeftInverseRange =
{$ifdef CPU64} 0..93 {$else} 0..47 {$endif};
/// domain for Fibonacci function
/// where result is within nativeUInt
// You can not name it fibonacciDomain,
// since the Fibonacci function itself
// is defined for all whole numbers
// but the result beyond F(n) exceeds high(nativeUInt).
fibonacciLeftInverseRange =
{$ifdef CPU64} 0..93 {$else} 0..47 {$endif};
{**
implements Fibonacci sequence iteratively
\param n the index of the Fibonacci number to calculate
\returns the Fibonacci value at n
implements Fibonacci sequence iteratively
\param n the index of the Fibonacci number to calculate
\returns the Fibonacci value at n
}
function fibonacci(const n: fibonacciLeftInverseRange): nativeUInt;
type
/// more meaningful identifiers than simple integers
relativePosition = (previous, current, next);
/// more meaningful identifiers than simple integers
relativePosition = (previous, current, next);
var
/// temporary iterator variable
i: longword;
/// holds preceding fibonacci values
f: array[relativePosition] of nativeUInt;
/// temporary iterator variable
i: longword;
/// holds preceding fibonacci values
f: array[relativePosition] of nativeUInt;
begin
f[previous] := 0;
f[current] := 1;
// note, in Pascal for-loop-limits are inclusive
for i := 1 to n do
begin
f[next] := f[previous] + f[current];
f[previous] := f[current];
f[current] := f[next];
end;
// assign to previous, bc f[current] = f[next] for next iteration
fibonacci := f[previous];
f[previous] := 0;
f[current] := 1;
// note, in Pascal for-loop-limits are inclusive
for i := 1 to n do
begin
f[next] := f[previous] + f[current];
f[previous] := f[current];
f[current] := f[next];
end;
// assign to previous, bc f[current] = f[next] for next iteration
fibonacci := f[previous];
end;

View file

@ -0,0 +1,7 @@
pub fn fib(n: Int) -> Int {
case n {
0 -> 0
1 -> 1
n -> fib(n - 1) + fib(n - 2)
}
}

View file

@ -0,0 +1,10 @@
pub fn fib(n: Int) -> Int {
fib_helper(n, 0, 1)
}
fn fib_helper(n: Int, res: Int, next: Int) -> Int {
case n, res, next {
0, res, _ -> res
iter, res, next -> fib_helper(iter - 1, next, res + next)
}
}

View file

@ -1,15 +1,15 @@
import (
"math/big"
"math/big"
)
func fib(n uint64) *big.Int {
if n < 2 {
return big.NewInt(int64(n))
}
a, b := big.NewInt(0), big.NewInt(1)
for n--; n > 0; n-- {
a.Add(a, b)
a, b = b, a
}
return b
if n < 2 {
return big.NewInt(int64(n))
}
a, b := big.NewInt(0), big.NewInt(1)
for n--; n > 0; n-- {
a.Add(a, b)
a, b = b, a
}
return b
}

View file

@ -1,16 +1,16 @@
func fibNumber() func() int {
fib1, fib2 := 0, 1
return func() int {
fib1, fib2 = fib2, fib1 + fib2
return fib1
}
fib1, fib2 := 0, 1
return func() int {
fib1, fib2 = fib2, fib1 + fib2
return fib1
}
}
func fibSequence(n int) int {
f := fibNumber()
fib := 0
for i := 0; i < n; i++ {
fib = f()
}
return fib
f := fibNumber()
fib := 0
for i := 0; i < n; i++ {
fib = f()
}
return fib
}

View file

@ -1,15 +1,15 @@
func fib(c chan int) {
a, b := 0, 1
for {
c <- a
a, b = b, a+b
}
a, b := 0, 1
for {
c <- a
a, b = b, a+b
}
}
func main() {
c := make(chan int)
go fib(c)
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
c := make(chan int)
go fib(c)
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
}

View file

@ -1,9 +1,9 @@
#include "harbour.ch"
Function fibb(n)
local fnow:=0, fnext:=1, tempf
while (--n>0)
tempf:=fnow+fnext
fnow:=fnext
fnext:=tempf
end while
return(fnext)
local fnow:=0, fnext:=1, tempf
while (--n>0)
tempf:=fnow+fnext
fnow:=fnext
fnext:=tempf
end while
return(fnext)

View file

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

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

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

View file

@ -0,0 +1 @@
long fib(int n) { n <= 2 ? 1 : fib(n-1) + fib(n-2) }

View file

@ -3,22 +3,22 @@
*/
public static long fib(long n) {
if (n <= 0)
return 0;
return 0;
long i = (int) (n - 1);
long a = 1, b = 0, c = 0, d = 1, tmp1,tmp2;
while (i > 0) {
if (i % 2 != 0) {
if (i % 2 != 0) {
tmp1 = d * b + c * a;
tmp2 = d * (b + a) + c * b;
a = tmp1;
b = tmp2;
}
tmp2 = d * (b + a) + c * b;
a = tmp1;
b = tmp2;
}
tmp1 = (long) (Math.pow(c, 2) + Math.pow(d, 2));
tmp2 = d * (2 * c + d);
c = tmp1;
d = tmp2;

View file

@ -13,20 +13,20 @@ $sequence = "";
// Prepare a loop
$i = 0;
:calcnextnumber;
$i = $i++;
$i = $i++;
// Do the calculation for this loop iteration
$b = $a + $b;
$a = $b - $a;
// Do the calculation for this loop iteration
$b = $a + $b;
$a = $b - $a;
// Add the result to the sequence
$sequence = $sequence << $a;
// Add the result to the sequence
$sequence = $sequence << $a;
// Make the loop run a fixed number of times
if $i < $n; {
$sequence = $sequence << ", ";
goto calcnextnumber;
}
// Make the loop run a fixed number of times
if $i < $n; {
$sequence = $sequence << ", ";
goto calcnextnumber;
}
// Use the loop counter as the placeholder
$i--;

View file

@ -1,15 +1,15 @@
integer Fibonacci(integer n) {
if(n<2) {
return n;
} else {
return Fibonacci(n-1)+Fibonacci(n-2);
}
if(n<2) {
return n;
} else {
return Fibonacci(n-1)+Fibonacci(n-2);
}
}
default {
state_entry() {
integer x = 0;
for(x=0 ; x<35 ; x++) {
llOwnerSay("Fibonacci("+(string)x+")="+(string)Fibonacci(x));
}
}
state_entry() {
integer x = 0;
for(x=0 ; x<35 ; x++) {
llOwnerSay("Fibonacci("+(string)x+")="+(string)Fibonacci(x));
}
}
}

View file

@ -1,18 +1,18 @@
fp.fib = ($n) -> {
if($n < 2) {
return $n
}
$prev = 1
$cur = 1
$i = 2
while($i < $n) {
$tmp = $cur
$cur += $prev
$prev = $tmp
$i += 1
}
return $cur
if($n < 2) {
return $n
}
$prev = 1
$cur = 1
$i = 2
while($i < $n) {
$tmp = $cur
$cur += $prev
$prev = $tmp
$i += 1
}
return $cur
}

View file

@ -1,7 +1,7 @@
fp.fib = ($n) -> {
if($n < 2) {
return $n
}
return parser.op(fp.fib($n - 1) + fp.fib($n - 2))
if($n < 2) {
return $n
}
return parser.op(fp.fib($n - 1) + fp.fib($n - 2))
}

View file

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

View file

@ -0,0 +1,7 @@
val fibonacci = fn(x number) {
for[f=[0, 1]] of x-1 {
f ~= [f[-1]+f[-2]]
}
}
writeln fibonacci(20)

View file

@ -1,19 +1,19 @@
define fibonacci(n::integer) => {
#n < 1 ? return false
#n < 1 ? return false
local(
swap = 0,
n1 = 0,
n2 = 1
)
local(
swap = 0,
n1 = 0,
n2 = 1
)
loop(#n) => {
loop(#n) => {
#swap = #n1 + #n2;
#n2 = #n1;
#n1 = #swap;
}
return #n1
}
return #n1
}

View file

@ -1,6 +1,6 @@
function f = fib(n)
f = [1 1 ; 1 0]^(n-1);
f = f(1,1);
f = [1 1 ; 1 0]^(n-1);
f = f(1,1);
end

View file

@ -1,43 +1,43 @@
.text
main: li $v0, 5 # read integer from input. The read integer will be stroed in $v0
syscall
beq $v0, 0, is1
beq $v0, 1, is1
li $s4, 1 # the counter which has to equal to $v0
li $s0, 1
li $s1, 1
.text
main: li $v0, 5 # read integer from input. The read integer will be stroed in $v0
syscall
loop: add $s2, $s0, $s1
addi $s4, $s4, 1
beq $v0, $s4, iss2
add $s0, $s1, $s2
addi $s4, $s4, 1
beq $v0, $s4, iss0
add $s1, $s2, $s0
addi $s4, $s4, 1
beq $v0, $s4, iss1
beq $v0, 0, is1
beq $v0, 1, is1
b loop
li $s4, 1 # the counter which has to equal to $v0
iss0: move $a0, $s0
b print
li $s0, 1
li $s1, 1
iss1: move $a0, $s1
b print
loop: add $s2, $s0, $s1
addi $s4, $s4, 1
beq $v0, $s4, iss2
iss2: move $a0, $s2
b print
is1: li $a0, 1
b print
print: li $v0, 1
syscall
li $v0, 10
syscall
add $s0, $s1, $s2
addi $s4, $s4, 1
beq $v0, $s4, iss0
add $s1, $s2, $s0
addi $s4, $s4, 1
beq $v0, $s4, iss1
b loop
iss0: move $a0, $s0
b print
iss1: move $a0, $s1
b print
iss2: move $a0, $s2
b print
is1: li $a0, 1
b print
print: li $v0, 1
syscall
li $v0, 10
syscall

View file

@ -0,0 +1,33 @@
' Fibonacci sequence
BEGIN DEF
pointer dword FibPtr~ ' Why "pointer dword" must be in lower case?
SUB CalcFib(N%, FibPtr~)
BEGIN CODE
PRINT "Enter n for fib(n): "
INPUT SN$
N% = VAL(SN$)
PRINT "\n"
CALL CalcFib(N%, VARPTR(Fib&))
PRINT Fib& + "\n"
END
SUB CalcFib(N%, FibPtr~)
IF N% = 0 THEN
Fib& = 0
ELSE
IF N% = 1 THEN
Fib& = 1
ELSE
Prev& = 0
Fib& = 1
FOR I% = 2 TO N%
T& = Fib&
Fib& = Prev& + Fib&
Prev& = T&
NEXT
ENDIF
ENDIF
[FibPtr~] = Fib&
END SUB

View file

@ -1,11 +1,11 @@
F fib(n:Int) {
n < 2 returns n
local a = 1, b = 1
# i is automatically local because of for()
for(i=2; i<n; i=i+1) {
local next = a + b
a = b
b = next
}
b
n < 2 returns n
local a = 1, b = 1
# i is automatically local because of for()
for(i=2; i<n; i=i+1) {
local next = a + b
a = b
b = next
}
b
}

View file

@ -6,7 +6,7 @@ def fibIter(n)
$fib = 1
$fibPrev = 1
for num in range(2, n - 1)
for num in range(2, n - 1)
fib += fibPrev
fibPrev = fib - fibPrev
end for

View file

@ -1,15 +1,15 @@
;;; Global variable (bigints); can be isolated in a namespace if need be
;;; Global variable (bigints); can be isolated in a namespace if need be
(setq stack '(0L 1L))
;
;;; If the stack is too short, complete it; then read from it
;;; Adding at the end of a list is optimized in NewLisp
;;; If the stack is too short, complete it; then read from it
;;; Adding at the end of a list is optimized in NewLisp
(define (fib n)
(while (<= (length stack) n)
(push (+ (stack -1) (stack -2)) stack -1))
(stack n))
(while (<= (length stack) n)
(push (+ (stack -1) (stack -2)) stack -1))
(stack n))
;
;;; Test (~ 7+ s on my mediocre laptop)
;(println (time (fib 50000)))
;;; or
;;; or
(println (length (fib 50000)))
;;; outputs 10450 (digits)
;;; outputs 10450 (digits)

View file

@ -2,11 +2,11 @@ package fib
import "core:fmt"
main :: proc() {
fmt.println("\nFibonacci Seq - starting n and n+1 from 0 and 1:")
fmt.println("------------------------------------------------")
for j: u128 = 0; j <= 20; j += 1 {
fmt.println("n:", j, "\tFib:", fibi(j))
}
fmt.println("\nFibonacci Seq - starting n and n+1 from 0 and 1:")
fmt.println("------------------------------------------------")
for j: u128 = 0; j <= 20; j += 1 {
fmt.println("n:", j, "\tFib:", fibi(j))
}
}
fibi :: proc(n: u128) -> u128 {

View file

@ -1,9 +1,9 @@
fun{Fib N}
fun{Loop N A B}
if N == 0 then
B
B
else
{Loop N-1 A+B A}
{Loop N-1 A+B A}
end
end
in

View file

@ -9,9 +9,47 @@ Program FastFibonacciGMP;
// AI Assistant: DeepSeek
// Description: Multiple Fibonacci algorithms with arbitrary precision
// AI translated from my own 2016 python app ( the hybrid part )
// License: Public Domain for Rosetta Code contribution
//
// LICENSE & ATTRIBUTION:
// ----------------------------------------------------------------------------
// 1. This Pascal source file (`FastFibonacciGMP.pas`) is released to the
// PUBLIC DOMAIN for Rosetta Code contribution. Author waives all copyright.
//
// 2. This program uses the Free Pascal `GMP` unit, which is a binding to the
// GNU MP Library (GMP). The `GMP` unit is part of Free Pascal's RTL-extra
// package, licensed under the GNU Lesser General Public License (LGPL)
// with a static linking exception.
//
// 3. The underlying GNU MP Library (libgmp) itself is licensed under:
// - GNU Lesser General Public License version 3 or later (LGPLv3+), OR
// - GNU General Public License version 2 or later (GPLv2+).
//
// 4. When compiled, this program links to the external GMP C library.
// For license compliance, users must have access to the GMP library
// source code (available at https://gmplib.org/).
// ============================================================================
// MATHEMATICAL FOUNDATION ATTRIBUTION:
// ----------------------------------------------------------------------------
// 1. Fast Doubling Formulas (Fibonacci Squaring):
// F(2k) = F(k) × [2×F(k+1) - F(k)]
// F(2k+1) = F(k+1)² + F(k)²
// Derived from Cassini's identity (1680) and Catalan's identity (1879).
// Modern algorithmic presentation: Dijkstra (1978), Cohn (1963).
//
// 2. Fibonacci Tripling Formulas:
// F(3k) = 5×F(k)³ + 3×(-1)×F(k)
// F(3k+1) = F(k+1)³ + 3×F(k+1)×F(k)² - F(k)³
// Derived from Binet's formula (1843).
// Algorithmic optimization: Various number theory sources.
//
// 3. Hybrid Decomposition Algorithm:
// Recursive decomposition using factors 2 and 3 based on divisibility.
// Original implementation concept: jpd (2016 Python implementation).
// Ported to Pascal with algorithmic corrections: DeepSeek AI (2025).
//
// NOTE: These mathematical identities are in the public domain.
// This specific implementation is original work.
// ----------------------------------------------------------------------------
Uses
SysUtils,
DateUtils,

View file

@ -6,11 +6,11 @@ function Fibo_BigInt(n: integer): string; //maXbox
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;
tbig1.assign(tbig2)
tbig2.assign(tbig3);
tbig1.add(tbig3);
tbig3.assign(tbig1);
end;
result:= tbig2.toString(false)
tbig3.free;
tbig2.free;

View file

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

View file

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

View file

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

View file

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

@ -43,9 +43,9 @@ fib(2, 1) :- !.
fib(1, 1) :- !.
fib(0, 0) :- !.
fib(A, D) :-
B is A+ -1,
fib(B, E),
C is A+ -2,
fib(C, F),
D is E+F,
asserta((fib(A, D):-!)).
B is A+ -1,
fib(B, E),
C is A+ -2,
fib(C, F),
D is E+F,
asserta((fib(A, D):-!)).

View file

@ -1,13 +1,13 @@
:- use_module(lambda).
fib(N, FN) :-
cont_fib(N, _, FN, \_^Y^_^U^(U = Y)).
cont_fib(N, _, FN, \_^Y^_^U^(U = Y)).
cont_fib(N, FN1, FN, Pred) :-
( N < 2 ->
call(Pred, 0, 1, FN1, FN)
;
N1 is N - 1,
P = \X^Y^Y^U^(U is X + Y),
cont_fib(N1, FNA, FNB, P),
call(Pred, FNA, FNB, FN1, FN)
).
( N < 2 ->
call(Pred, 0, 1, FN1, FN)
;
N1 is N - 1,
P = \X^Y^Y^U^(U is X + Y),
cont_fib(N1, FNA, FNB, P),
call(Pred, FNA, FNB, FN1, FN)
).

View file

@ -1,3 +1,3 @@
Macro Fibonacci (n)
Int((Pow(((1+Sqr(5))/2),n)-Pow(((1-Sqr(5))/2),n))/Sqr(5))
Int((Pow(((1+Sqr(5))/2),n)-Pow(((1-Sqr(5))/2),n))/Sqr(5))
EndMacro

View file

@ -0,0 +1,6 @@
fibseq = [1,1,]
fiblength = 21
for x in range(1,fiblength-1):
xcount = fibseq[x-1] + fibseq[x]
fibseq.append(xcount)
print(xcount)

View file

@ -1,11 +1,11 @@
def analytic_fibonacci91(m):
"""
Binet's algebraic formula for the nth Fibonacci number.
Good for up to n=91
Uses numpy longdoubles:
"""
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
"""
See: https://artofproblemsolving.com/wiki/index.php/Binet%27s_Formula
"""
import numpy as np
assert isinstance(m,int), "parameter must be an integer."

View file

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

View file

@ -1,45 +1,45 @@
class FibonacciSequence
**Prints the nth fibonacci number**
on start
args := program arguments
if args empty
print .fibonacci(8)
else
try
print .fibonacci(integer.parse(args[0]))
catch FormatException
print to Console.error made !, "Input must be an integer"
exit program with error code
catch OverflowException
print to Console.error made !, "Number too large"
exit program with error code
define fibonacci(n as integer) as integer is shared
**Returns the nth fibonacci number**
test
assert fibonacci(0) = 0
assert fibonacci(1) = 1
assert fibonacci(2) = 1
assert fibonacci(3) = 2
assert fibonacci(4) = 3
assert fibonacci(5) = 5
assert fibonacci(6) = 8
assert fibonacci(7) = 13
assert fibonacci(8) = 21
**Prints the nth fibonacci number**
body
a, b := 0, 1
for n
a, b := b, a + b
return a
on start
args := program arguments
if args empty
print .fibonacci(8)
else
try
print .fibonacci(integer.parse(args[0]))
catch FormatException
print to Console.error made !, "Input must be an integer"
exit program with error code
catch OverflowException
print to Console.error made !, "Number too large"
exit program with error code
define fibonacci(n as integer) as integer is shared
**Returns the nth fibonacci number**
test
assert fibonacci(0) = 0
assert fibonacci(1) = 1
assert fibonacci(2) = 1
assert fibonacci(3) = 2
assert fibonacci(4) = 3
assert fibonacci(5) = 5
assert fibonacci(6) = 8
assert fibonacci(7) = 13
assert fibonacci(8) = 21
body
a, b := 0, 1
for n
a, b := b, a + b
return a

View file

@ -0,0 +1,20 @@
Rebol [
title: "Rosetta code: Fibonacci sequence"
file: %Fibonacci_sequence.r3
url: https://rosettacode.org/wiki/Fibonacci_sequence
]
fibonacci: function/with [
{Return the Nth Fibonacci number using iterative state advancement.
Uses a shared block to swap fn and fn-1 in a single expression.}
number [integer!] "which Fibonacci number to compute (0-indexed)"
][
fn-1: 0 ;; F(0)
fn: 1 ;; F(1)
loop number advance-fibonacci
][
fn: fn-1: 0
advance-fibonacci: [ fn: fn-1 + fn-1: fn ] ;; simultaneously: new fn = old fn + old fn-1
]
probe collect [repeat i 18 [keep fibonacci i]]

View file

@ -2,7 +2,7 @@ Red []
palindrome: [fn: fn-1 + fn-1: fn]
fibonacci: func [n][
fn-1: 0
fn: 1
loop n palindrome
fn-1: 0
fn: 1
loop n palindrome
]

View file

@ -0,0 +1,8 @@
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,8 @@
define("fib(a)") :(fib_end)
fib fib = lt(a,2) a :s(return)
fib = fib(a - 1) + fib(a - 2) :(return)
define("fib(a)") :(fib_end)
fib fib = lt(a,2) a :s(return)
fib = fib(a - 1) + fib(a - 2) :(return)
fib_end
while a = trim(input) :f(end)
output = a " " fib(a) :(while)
while a = trim(input) :f(end)
output = a " " fib(a) :(while)
end

View file

@ -0,0 +1,29 @@
(define (fast-fib-pair n)
;; By Arnold Schönhage, personal communication, 2004
;; returns f_n f_{n+1}
(case n
((1) (values 1 1))
((2) (values 1 2))
(else
(let ((m (quotient n 2)))
(call-with-values
(lambda () (fast-fib-pair m))
(lambda (f_m f_m+1)
(let ((f_m^2 (square f_m))
(f_m+1^2 (square f_m+1)))
(if (even? n)
(values (- (* 2 f_m+1^2)
(* 3 f_m^2)
(if (odd? m) -2 2))
(+ f_m^2 f_m+1^2))
(values (+ f_m^2 f_m+1^2)
(- (* 3 f_m+1^2)
(* 2 f_m^2)
(if (odd? m) -2 2)))))))))))
(call-with-values
(lambda ()
(fast-fib-pair 100000000))
(lambda (f_n f_n+1)
(display (list (modulo f_n 100000) (modulo f_n+1 100000)))
(newline)))

View file

@ -1,4 +1,4 @@
fibonacci(n) :=
n when n < 2
else
fibonacci(n - 1) + fibonacci(n - 2);
n when n < 2
else
fibonacci(n - 1) + fibonacci(n - 2);

View file

@ -1,8 +1,8 @@
fibonacci(n) := fibonacciHelper(0, 1, n);
fibonacciHelper(prev, next, n) :=
prev when n < 1
else
next when n = 1
else
fibonacciHelper(next, next + prev, n - 1);
prev when n < 1
else
next when n = 1
else
fibonacciHelper(next, next + prev, n - 1);

View file

@ -1,11 +1,11 @@
fibonacci(n) := fibonacciHelper([[1,0],[0,1]], n);
fibonacciHelper(M(2), n) :=
let
N := [[1,1],[1,0]];
in
M[1,1] when n <= 1
else
fibonacciHelper(matmul(M, N), n - 1);
let
N := [[1,1],[1,0]];
in
M[1,1] when n <= 1
else
fibonacciHelper(matmul(M, N), n - 1);
matmul(A(2), B(2)) [i,j] := sum( A[i,all] * B[all,j] );

View file

@ -1,7 +1,7 @@
fun fib n =
let
fun fib' (0,a,b) = a
| fib' (n,a,b) = fib' (n-1,a+b,a)
fun fib' (0,a,b) = a
| fib' (n,a,b) = fib' (n-1,a+b,a)
in
fib' (n,0,1)
fib' (n,0,1)
end

View file

@ -4,7 +4,7 @@ clear
qui set obs `n'
qui gen a=.
dyngen {
update a=a[_n-1]+a[_n-2], missval(1)
update a=a[_n-1]+a[_n-2], missval(1)
}
end

View file

@ -1,9 +1,9 @@
(
f = { |n|
var sqrt5 = sqrt(5);
var p = (1 + sqrt5) / 2;
var q = reciprocal(p);
((p ** n) + (q ** n) / sqrt5 + 0.5).trunc
};
(0..20).collect(f)
f = { |n|
var sqrt5 = sqrt(5);
var p = (1 + sqrt5) / 2;
var q = reciprocal(p);
((p ** n) + (q ** n) / sqrt5 + 0.5).trunc
};
(0..20).collect(f)
)

View file

@ -3,18 +3,18 @@ nMin=0
u(n)=u(n-1)+u(n-2)
u(nMin)={1,0}
[TABLE]
n u(n)
------- -------
0 0
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34
10 55
11 89
12 144
n u(n)
------- -------
0 0
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34
10 55
11 89
12 144

View file

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

View file

@ -0,0 +1,3 @@
15 # length of final array
[1 1] # starting two values in the sequence
⊙◌⍢(⊂/+⊸↙2|>⧻) # do iteration while less than desired length

View file

@ -1,12 +1,12 @@
def fibIter (int n)
if (< n 2)
return n
end if
decl int fib fibPrev num
set fib (set fibPrev 1)
for (set num 2) (< num n) (inc num)
set fib (+ fib fibPrev)
set fibPrev (- fib fibPrev)
end for
return fib
if (< n 2)
return n
end if
decl int fib fibPrev num
set fib (set fibPrev 1)
for (set num 2) (< num n) (inc num)
set fib (+ fib fibPrev)
set fibPrev (- fib fibPrev)
end for
return fib
end

View file

@ -6,8 +6,8 @@
#1400
&loop
DUP #00 SWP fibonacci print/dec newline
INC GTHk ?&loop
DUP #00 SWP fibonacci print/dec newline
INC GTHk ?&loop
POP2
BRK
@ -18,14 +18,14 @@ BRK
DUP2 #0001 SUB2 fibonacci STH2
#0002 SUB2 fibonacci
STH2r ADD2
JMP2r
JMP2r
@print/dec ( short* -- )
#000a SWP2 [ LITr ff ]
&get ( -- )
SWP2k DIV2k MUL2 SUB2 STH
POP OVR2 DIV2 ORAk ?&get
POP2 POP2
&put ( -- )
STHr INCk ?{ POP JMP2r }
[ LIT "0 ] ADD .Console/write DEO !&put
#000a SWP2 [ LITr ff ]
&get ( -- )
SWP2k DIV2k MUL2 SUB2 STH
POP OVR2 DIV2 ORAk ?&get
POP2 POP2
&put ( -- )
STHr INCk ?{ POP JMP2r }
[ LIT "0 ] ADD .Console/write DEO !&put

View file

@ -1,23 +1,23 @@
0000 0000 1 .entry main,0
7E 7CFD 0002 2 clro -(sp) ;result buffer
5E DD 0005 3 pushl sp ;pointer to buffer
10 DD 0007 4 pushl #16 ;descriptor: len of buffer
5B 5E D0 0009 5 movl sp, r11 ;-> descriptor
0000 0000 1 .entry main,0
7E 7CFD 0002 2 clro -(sp) ;result buffer
5E DD 0005 3 pushl sp ;pointer to buffer
10 DD 0007 4 pushl #16 ;descriptor: len of buffer
5B 5E D0 0009 5 movl sp, r11 ;-> descriptor
000C 6
7E 01 7D 000C 7 movq #1, -(sp) ;init 0,1
7E 01 7D 000C 7 movq #1, -(sp) ;init 0,1
000F 8 loop:
7E 6E 04 AE C1 000F 9 addl3 4(sp), (sp), -(sp) ;next element on stack
17 1D 0014 10 bvs ret ;vs - overflow set, exit
7E 6E 04 AE C1 000F 9 addl3 4(sp), (sp), -(sp) ;next element on stack
17 1D 0014 10 bvs ret ;vs - overflow set, exit
0016 11
5B DD 0016 12 pushl r11 ;-> descriptor by ref
04 AE DF 0018 13 pushal 4(sp) ;-> fib on stack by ref
00000000'GF 02 FB 001B 14 calls #2, g^ots$cvt_l_ti ;convert integer to string
5B DD 0022 15 pushl r11 ;
00000000'GF 01 FB 0024 16 calls #1, g^lib$put_output ;show result
E2 11 002B 17 brb loop
5B DD 0016 12 pushl r11 ;-> descriptor by ref
04 AE DF 0018 13 pushal 4(sp) ;-> fib on stack by ref
00000000'GF 02 FB 001B 14 calls #2, g^ots$cvt_l_ti ;convert integer to string
5B DD 0022 15 pushl r11 ;
00000000'GF 01 FB 0024 16 calls #1, g^lib$put_output ;show result
E2 11 002B 17 brb loop
002D 18 ret:
04 002D 19 ret
002E 20 .end main
04 002D 19 ret
002E 20 .end main
$ run fib
...
14930352

View file

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

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

View file

@ -1,6 +1,6 @@
int fibRec(int n){
if (n < 2)
return n;
else
return fibRec(n - 1) + fibRec(n - 2);
if (n < 2)
return n;
else
return fibRec(n - 1) + fibRec(n - 2);
}

View file

@ -1,16 +1,16 @@
int fibIter(int n){
if (n < 2)
return n;
int last = 0;
int cur = 1;
int next;
for (int i = 1; i < n; ++i){
next = last + cur;
last = cur;
cur = next;
}
return cur;
if (n < 2)
return n;
int last = 0;
int cur = 1;
int next;
for (int i = 1; i < n; ++i){
next = last + cur;
last = cur;
cur = next;
}
return cur;
}

View file

@ -12,38 +12,38 @@ if (#1 < 2) {
IC('1') IN
#10 = #1
While (#10 > 1) {
#12 = 0 // carry out
#15 = 1 // column (ones, tens, hundreds...)
Repeat (ALL) { // Sum all columns
Line(-1) // n-1
Goto_col(#15)
if (At_EOL) { // all digits added
break
}
#11 = Cur_Char - '0' + #12 // digit of (n-1) + carry
Line(-1) // n-2
Goto_Col(#15)
if (!At_EOL) { // may contain fewer digits than n-1
#11 += Cur_Char - '0'
}
Goto_Line(3) // sum
EOL
#12 = #11 / 10 // carry out
Ins_Char((#11 % 10) + '0')
#15++ // next column
}
if (#12) {
Goto_Line(3)
EOL
Ins_Char(#12 + '0') // any extra digit from carry
#12 = 0 // carry out
#15 = 1 // column (ones, tens, hundreds...)
Repeat (ALL) { // Sum all columns
Line(-1) // n-1
Goto_col(#15)
if (At_EOL) { // all digits added
break
}
#11 = Cur_Char - '0' + #12 // digit of (n-1) + carry
Line(-1) // n-2
Goto_Col(#15)
if (!At_EOL) { // may contain fewer digits than n-1
#11 += Cur_Char - '0'
}
Goto_Line(3) // sum
EOL
#12 = #11 / 10 // carry out
Ins_Char((#11 % 10) + '0')
#15++ // next column
}
if (#12) {
Goto_Line(3)
EOL
Ins_Char(#12 + '0') // any extra digit from carry
}
BOF
Del_Line(1) // Next n
Line(1) EOL
Ins_Newline
#10--
BOF
Del_Line(1) // Next n
Line(1) EOL
Ins_Newline
#10--
}
Goto_Line(2) // Results on line 2
Goto_Line(2) // Results on line 2
}
// Copy the results to text register 10 in reverse order
Reg_Empty(10)

View file

@ -2,9 +2,9 @@ let s => import 'stream';
let a => import 'arrays';
let fib n => (
let reducer p n => [a.at p 1; + (a.at p 0) (a.at p 1)];
s.range 1 n
-> s.reduce [0; 1] reducer
-> a.at 1
;
let reducer p n => [a.at p 1; + (a.at p 0) (a.at p 1)];
s.range 1 n
-> s.reduce [0; 1] reducer
-> a.at 1
;
);

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