September Morn Update

This commit is contained in:
Ingy döt Net 2019-09-12 10:33:56 -07:00
parent 4e2d22a71d
commit aac6731f2c
6856 changed files with 141342 additions and 21127 deletions

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

@ -1,14 +1,24 @@
FUNCTION itFib (n)
n1 = 0
n2 = 1
FOR k = 1 TO ABS(n)
sum = n1 + n2
n1 = n2
n2 = sum
NEXT k
IF n < 0 THEN
itFib = n1 * ((-1) ^ ((-n) + 1))
ELSE
itFib = n1
END IF
END FUNCTION
# 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,9 @@
10 INPUT N
20 LET A=0
30 LET B=1
40 FOR I=2 TO N
50 LET C=B
60 LET B=A+B
70 LET A=C
80 NEXT I
90 PRINT B

View file

@ -0,0 +1,13 @@
10 INPUT N
20 LET A=0
30 LET B=1
40 GOSUB 70
50 PRINT B
60 STOP
70 IF N=1 THEN RETURN
80 LET C=B
90 LET B=A+B
100 LET A=C
110 LET N=N-1
120 GOSUB 70
130 RETURN

View file

@ -1,38 +1,8 @@
DECLARE FUNCTION fibonacci& (n AS INTEGER)
REDIM SHARED fibNum(1) AS LONG
fibNum(1) = 1
'*****sample inputs*****
PRINT fibonacci(0) 'no calculation needed
PRINT fibonacci(13) 'figure F(2)..F(13)
PRINT fibonacci(-42) 'figure F(14)..F(42)
PRINT fibonacci(47) 'error: too big
'*****sample inputs*****
FUNCTION fibonacci& (n AS INTEGER)
DIM a AS INTEGER
a = ABS(n)
SELECT CASE a
CASE 0 TO 46
SHARED fibNum() AS LONG
DIM u AS INTEGER, L0 AS INTEGER
u = UBOUND(fibNum)
IF a > u THEN
REDIM PRESERVE fibNum(a) AS LONG
FOR L0 = u + 1 TO a
fibNum(L0) = fibNum(L0 - 1) + fibNum(L0 - 2)
NEXT
END IF
IF n < 0 THEN
fibonacci = fibNum(a) * ((-1) ^ (a + 1))
ELSE
fibonacci = fibNum(n)
END IF
CASE ELSE
'limited to signed 32-bit int (LONG)
'F(47)=&hB11924E1
ERROR 6 'overflow
END SELECT
END FUNCTION
10 INPUT "ENTER VALUE OF N"; N
20 N1 = 0 : N2 = 1
30 FOR K=1 TO N
40 SUM = N1+N2
50 N1 = N2
60 N2 = SUM
70 NEXT K
80 PRINT N1

View file

@ -1,7 +1,10 @@
FUNCTION recFib (n)
IF (n < 2) THEN
recFib = n
ELSE
recFib = recFib(n - 1) + recFib(n - 2)
END IF
END FUNCTION
10 INPUT N
20 A=0
30 B=1
40 FOR I=2 TO N
50 C=B
60 B=A+B
70 A=C
80 NEXT I
90 PRINT B
100 END

View file

@ -1,21 +1,12 @@
DATA -1836311903,1134903170,-701408733,433494437,-267914296,165580141,-102334155
DATA 63245986,-39088169,24157817,-14930352,9227465,-5702887,3524578,-2178309
DATA 1346269,-832040,514229,-317811,196418,-121393,75025,-46368,28657,-17711
DATA 10946,-6765,4181,-2584,1597,-987,610,-377,233,-144,89,-55,34,-21,13,-8,5,-3
DATA 2,-1,1,0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765
DATA 10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269
DATA 2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986
DATA 102334155,165580141,267914296,433494437,701408733,1134903170,1836311903
DIM fibNum(-46 TO 46) AS LONG
FOR n = -46 TO 46
READ fibNum(n)
NEXT
'*****sample inputs*****
FOR n = -46 TO 46
PRINT fibNum(n),
NEXT
PRINT
'*****sample inputs*****
100 PROGRAM "Fibonac.bas"
110 FOR I=0 TO 20
120 PRINT "F";I,FIB(I)
130 NEXT
140 DEF FIB(N)
150 NUMERIC I
160 LET A=0:LET B=1
170 FOR I=1 TO N
180 LET T=A+B:LET A=B:LET B=T
190 NEXT
200 LET FIB=A
210 END DEF

View file

@ -1,8 +1,14 @@
10 INPUT "ENTER VALUE OF N"; N
20 N1 = 0 : N2 = 1
30 FOR K=1 TO N
40 SUM = N1+N2
50 N1 = N2
60 N2 = SUM
70 NEXT K
80 PRINT N1
FUNCTION itFib (n)
n1 = 0
n2 = 1
FOR k = 1 TO ABS(n)
sum = n1 + n2
n1 = n2
n2 = sum
NEXT k
IF n < 0 THEN
itFib = n1 * ((-1) ^ ((-n) + 1))
ELSE
itFib = n1
END IF
END FUNCTION

View file

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

View file

@ -1,2 +1,7 @@
10 INPUT N
20 PRINT INT (0.5+(((SQR 5+1)/2)**N)/SQR 5)
FUNCTION recFib (n)
IF (n < 2) THEN
recFib = n
ELSE
recFib = recFib(n - 1) + recFib(n - 2)
END IF
END FUNCTION

View file

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

View file

@ -1,13 +1,2 @@
10 INPUT N
20 LET A=0
30 LET B=1
40 GOSUB 70
50 PRINT B
60 STOP
70 IF N=1 THEN RETURN
80 LET C=B
90 LET B=A+B
100 LET A=C
110 LET N=N-1
120 GOSUB 70
130 RETURN
20 PRINT INT (0.5+(((SQR 5+1)/2)**N)/SQR 5)

View file

@ -0,0 +1,16 @@
(ns fib.core)
(require '[clojure.core.async
:refer [<! >! >!! <!! timeout chan alt! go]])
(defn fib [c]
(loop [a 0 b 1]
(>!! c a)
(recur b (+ a b))))
(defn -main []
(let [c (chan)]
(go (fib c))
(dorun
(for [i (range 10)]
(println (<!! c))))))

View file

@ -1,6 +1,11 @@
(defn fib [n]
(case n
0 0
1 1
(+ (fib (- n 1))
(fib (- n 2)))))
(letfn [(fib* [n]
(if (zero? n)
[0 1]
(let [[a b] (fib* (quot n 2))
c (*' a (-' (*' 2 b) a))
d (+' (*' b b) (*' a a))]
(if (even? n)
[c d]
[d (+' c d)]))))]
(first (fib* n))))

View file

@ -1,8 +1,6 @@
(def fib
(memoize
(fn [n]
(case n
0 0
1 1
(+ (fib (- n 1))
(fib (- n 2)))))))
(defn fib [n]
(case n
0 0
1 1
(+ (fib (- n 1))
(fib (- n 2)))))

View file

@ -1,16 +1,8 @@
(ns fib.core)
(require '[clojure.core.async
:refer [<! >! >!! <!! timeout chan alt! go]])
(defn fib [c]
(loop [a 0 b 1]
(>!! c a)
(recur b (+ a b))))
(defn -main []
(let [c (chan)]
(go (fib c))
(dorun
(for [i (range 10)]
(println (<!! c))))))
(def fib
(memoize
(fn [n]
(case n
0 0
1 1
(+ (fib (- n 1))
(fib (- n 2)))))))

View file

@ -0,0 +1,8 @@
(defmethod fib (n)
(declare ((integer 0 *) n))
(+ (fib (- n 1))
(fib (- n 2))))
(defmethod fib ((n (eql 0))) 0)
(defmethod fib ((n (eql 1))) 1)

View file

@ -0,0 +1,17 @@
[ # todo: n(<2) -- 1 and break 2 levels
d - # 0
1 + # 1
q
] s1
[ # todo: n(>-1) -- F(n)
d 0=1 # n(!=0)
d 1=1 # n(!in {0,1})
2 - d 1 + # (n-2) (n-1)
lF x # (n-2) F(n-1)
r # F(n-1) (n-2)
lF x # F(n-1)+F(n-2)
+
] sF
33 lF x f

View file

@ -1,26 +1,29 @@
import extensions.
import extensions;
fibu = (:i)
[
var ac := Array new(2); populate(:i)(i).
if (i < 2)
[ ^ ac[i] ];
[
2 to:i do(:i)
[
var t := ac[1].
ac[1] := ac[0] + ac[1].
ac[0] := t.
].
fibu(n)
{
int[] ac := new int[] { 0,1 };
if (n < 2)
{
^ ac[n]
}
else
{
for(int i := 2, i <= n, i+=1)
{
int t := ac[1];
ac[1] := ac[0] + ac[1];
ac[0] := t
};
^ ac[1]
]
].
^ ac[1]
}
}
program =
[
0 to:10 do(:i)
[
console printLine(fibu(i)).
]
].
public program()
{
for(int i := 0, i <= 10, i+=1)
{
console.printLine(fibu(i))
}
}

View file

@ -1,6 +1,6 @@
-module(fib).
-export([fib/1]).
fib(0) -> 1;
fib(0) -> 0;
fib(1) -> 1;
fib(N) -> fib(N-1) + fib(N-2).

View file

@ -0,0 +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};
{**
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);
var
/// 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];
end;

View file

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

View file

@ -0,0 +1,70 @@
; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps
$"PRINT_LONG" = comdat any
@"PRINT_LONG" = linkonce_odr unnamed_addr constant [5 x i8] c"%ld\0A\00", comdat, align 1
;--- The declaration for the external C printf function.
declare i32 @printf(i8*, ...)
;--------------------------------------------------------------------
;-- Function for calculating the nth fibonacci numbers
;--------------------------------------------------------------------
define i32 @fibonacci(i32) {
%2 = alloca i32, align 4 ;-- allocate local copy of n
%3 = alloca i32, align 4 ;-- allocate a
%4 = alloca i32, align 4 ;-- allocate b
store i32 %0, i32* %2, align 4 ;-- store copy of n
store i32 0, i32* %3, align 4 ;-- a := 0
store i32 1, i32* %4, align 4 ;-- b := 1
br label %loop
loop:
%5 = load i32, i32* %2, align 4 ;-- load n
%6 = icmp sgt i32 %5, 0 ;-- n > 0
br i1 %6, label %loop_body, label %exit
loop_body:
%7 = load i32, i32* %3, align 4 ;-- load a
%8 = load i32, i32* %4, align 4 ;-- load b
%9 = add nsw i32 %7, %8 ;-- t = a + b
store i32 %8, i32* %3, align 4 ;-- store a = b
store i32 %9, i32* %4, align 4 ;-- store b = t
%10 = load i32, i32* %2, align 4 ;-- load n
%11 = add nsw i32 %10, -1 ;-- decrement n
store i32 %11, i32* %2, align 4 ;-- store n
br label %loop
exit:
%12 = load i32, i32* %3, align 4 ;-- load a
ret i32 %12 ;-- return a
}
;--------------------------------------------------------------------
;-- Main function for printing successive fibonacci numbers
;--------------------------------------------------------------------
define i32 @main() {
%1 = alloca i32, align 4 ;-- allocate index
store i32 0, i32* %1, align 4 ;-- index := 0
br label %loop
loop:
%2 = load i32, i32* %1, align 4 ;-- load index
%3 = icmp sle i32 %2, 12 ;-- index <= 12
br i1 %3, label %loop_body, label %exit
loop_body:
%4 = load i32, i32* %1, align 4 ;-- load index
%5 = call i32 @fibonacci(i32 %4)
%6 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"PRINT_LONG", i32 0, i32 0), i32 %5)
%7 = load i32, i32* %1, align 4 ;-- load index
%8 = add nsw i32 %7, 1 ;-- increment index
store i32 %8, i32* %1, align 4 ;-- store index
br label %loop
exit:
ret i32 0 ;-- return EXIT_SUCCESS
}

View file

@ -0,0 +1,4 @@
--calculates the nth fibonacci number. Breaks for negative or non-integer n.
function fibs(n)
return n < 2 and n or fibs(n - 1) + fibs(n - 2)
end

View file

@ -0,0 +1,8 @@
--more pedantic version, returns 0 for non-integer n
function pfibs(n)
if n ~= math.floor(n) then return 0
elseif n < 0 then return pfibs(n + 2) - pfibs(n + 1)
elseif n < 2 then return n
else return pfibs(n - 1) + pfibs(n - 2)
end
end

View file

@ -0,0 +1,2 @@
function a(n,u,s) if n<2 then return u+s end return a(n-1,u+s,u) end
function trfib(i) return a(i-1,1,0) end

View file

@ -0,0 +1 @@
fib_n = setmetatable({1, 1}, {__index = function(z,n) return n<=0 and 0 or z[n-1] + z[n-2] end})

View file

@ -0,0 +1,9 @@
-- table recursive done properly (values are actually saved into table;
-- also the first element of Fibonacci sequence is 0, so the initial table should be {0, 1}).
fib_n = setmetatable({0, 1}, {
__index = function(t,n)
if n <= 0 then return 0 end
t[n] = t[n-1] + t[n-2]
return t[n]
end
})

View file

@ -0,0 +1,5 @@
function ifibs(n)
local p0,p1=0,1
for _=1,n do p0,p1 = p1,p0+p1 end
return p0
end

View file

@ -1,37 +0,0 @@
--calculates the nth fibonacci number. Breaks for negative or non-integer n.
function fibs(n)
return n < 2 and n or fibs(n - 1) + fibs(n - 2)
end
--more pedantic version, returns 0 for non-integer n
function pfibs(n)
if n ~= math.floor(n) then return 0
elseif n < 0 then return pfibs(n + 2) - pfibs(n + 1)
elseif n < 2 then return n
else return pfibs(n - 1) + pfibs(n - 2)
end
end
--tail-recursive
function a(n,u,s) if n<2 then return u+s end return a(n-1,u+s,u) end
function trfib(i) return a(i-1,1,0) end
--table-recursive
fib_n = setmetatable({1, 1}, {__index = function(z,n) return n<=0 and 0 or z[n-1] + z[n-2] end})
--table-recursive done properly (values are actually saved into table; also the first element
-- of Fibonacci sequence is 0, so the initial table should be {0, 1}).
fib_n = setmetatable({0, 1}, {
__index = function(t,n)
if n <= 0 then return 0 end
t[n] = t[n-1] + t[n-2]
return t[n]
end
})
--loop version
function lfibs(n)
local p0,p1=0,1
for _=1,n do p0,p1 = p1,p0+p1 end
return p0
end

View file

@ -0,0 +1,36 @@
PROCEDURE IterFib(n: INTEGER): INTEGER =
VAR
limit := ABS(n);
prev := 0;
curr, next: INTEGER;
BEGIN
(* trivial case *)
IF n = 0 THEN RETURN 0; END;
IF n > 0 THEN (* positive case *)
curr := 1;
FOR i := 2 TO limit DO
next := prev + curr;
prev := curr;
curr := next;
END;
ELSE (* negative case *)
curr := -1;
FOR i := 2 TO limit DO
next := prev - curr;
prev := curr;
curr := next;
END;
END;
RETURN curr;
END IterFib;

View file

@ -1,21 +1,44 @@
include builtins\bigatom.e
-- demo\rosetta\fibonacci.exw
include mpfr.e
sequence fcacheba = {BA_ONE,BA_ONE}
mpz res = NULL, prev, next
integer lastn
atom t0 = time()
function fibonamemba(integer n) -- memoized, works for -ve numbers, yields bigatom
function fibonampz(integer n) -- resumable, works for -ve numbers, yields mpz
integer absn = abs(n)
if n=0 then return BA_ZERO end if
while length(fcacheba)<absn do
fcacheba = append(fcacheba,ba_add(fcacheba[$],fcacheba[$-1]))
end while
if n<0 and remainder(n,2)=0 then return ba_sub(0,fcacheba[absn]) end if
return fcacheba[absn]
if res=NULL or absn!=abs(lastn)+1 then
if res=NULL then
prev = mpz_init(0)
res = mpz_init(1)
next = mpz_init()
else
if n==lastn then return res end if
end if
mpz_fib2_ui(res,prev,absn)
else
if lastn<0 and remainder(lastn,2)=0 then
mpz_mul_si(res,res,-1)
end if
mpz_add(next,res,prev)
{prev,res,next} = {res,next,prev}
end if
if n<0 and remainder(n,2)=0 then
mpz_mul_si(res,res,-1)
end if
lastn = n
return res
end function
for i=0 to 28 do
if i then puts(1,", ") end if
ba_printf(1,"%B", fibonamemba(i))
printf(1,"%s", {mpz_get_str(fibonampz(i))})
end for
puts(1,"\n")
ba_printf(1,"%B", fibonamemba(705))
puts(1,"\n")
printf(1,"%s\n", {mpz_get_str(fibonampz(705))})
string s = mpz_get_str(fibonampz(4784969))
integer l = length(s)
s[40..-40] = "..."
?{l,s}
?elapsed(time()-t0)

View file

@ -0,0 +1,14 @@
void setup() {
size(400, 400);
fill(255, 64);
frameRate(2);
}
void draw() {
int num = fibonacciNum(frameCount);
println(frameCount, num);
rect(0,0,num, num);
if(frameCount==14) frameCount = -1; // restart
}
int fibonacciNum(int n) {
return (n < 2) ? n : fibonacciNum(n - 1) + fibonacciNum(n - 2);
}

View file

@ -0,0 +1,31 @@
'''Fibonacci accumulation'''
from itertools import (accumulate, chain)
# 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.
'''
def go(ab, _):
a, b = ab
return (b, a + b)
return [xy[1] for xy in accumulate(
chain(
[(0, 1)],
range(1, n)
),
go
)]
# MAIN ---
if __name__ == '__main__':
print(
'First twenty: ' + repr(
fibs(20)
)
)

View file

@ -0,0 +1,21 @@
'''Nth Fibonacci term (by folding)'''
from functools import (reduce)
# nthFib :: Integer -> Integer
def nthFib(n):
'''Nth integer in the Fibonacci series.'''
def go(ab, _):
a, b = ab
return (b, a + b)
return reduce(go, range(1, n), (0, 1))[1]
# MAIN ---
if __name__ == '__main__':
print(
'1000th term: ' + repr(
nthFib(1000)
)
)

View file

@ -3,20 +3,20 @@ numeric digits 210000 /*be able to handle ginormous n
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*/
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.*/
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│ */
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. */

View file

@ -1,14 +1,7 @@
#![feature(conservative_impl_trait)]
fn main() {
for num in fibonacci_gen(10) {
println!("{}", num);
fn fib(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
n => fib(n - 1) + fib(n - 2),
}
}
fn fibonacci_gen(terms: i32) -> impl Iterator<Item=u64> {
let sqrt_5 = 5.0f64.sqrt();
let p = (1.0 + sqrt_5) / 2.0;
let q = 1.0/p;
(1..terms).map(move |n| ((p.powi(n) + q.powi(n)) / sqrt_5 + 0.5) as u64)
}

View file

@ -1,29 +1,14 @@
use std::mem;
struct Fib {
prev: usize,
curr: usize,
}
impl Fib {
fn new() -> Self {
Fib {prev: 0, curr: 1}
}
}
impl Iterator for Fib {
type Item = usize;
fn next(&mut self) -> Option<Self::Item>{
mem::swap(&mut self.curr, &mut self.prev);
self.curr.checked_add(self.prev).map(|n| {
self.curr = n;
n
})
}
}
#![feature(conservative_impl_trait)]
fn main() {
for num in Fib::new() {
for num in fibonacci_gen(10) {
println!("{}", num);
}
}
fn fibonacci_gen(terms: i32) -> impl Iterator<Item=u64> {
let sqrt_5 = 5.0f64.sqrt();
let p = (1.0 + sqrt_5) / 2.0;
let q = 1.0/p;
(1..terms).map(move |n| ((p.powi(n) + q.powi(n)) / sqrt_5 + 0.5) as u64)
}

View file

@ -0,0 +1,29 @@
use std::mem;
struct Fib {
prev: usize,
curr: usize,
}
impl Fib {
fn new() -> Self {
Fib {prev: 0, curr: 1}
}
}
impl Iterator for Fib {
type Item = usize;
fn next(&mut self) -> Option<Self::Item>{
mem::swap(&mut self.curr, &mut self.prev);
self.curr.checked_add(self.prev).map(|n| {
self.curr = n;
n
})
}
}
fn main() {
for num in Fib::new() {
println!("{}", num);
}
}

View file

@ -0,0 +1,22 @@
con
_clkmode = xtal1 + pll16x
_clkfreq = 80_000_000
obj
ser : "FullDuplexSerial.spin"
pub main | i
ser.start(31, 30, 0, 115200)
repeat i from 0 to 10
ser.dec(fib(i))
ser.tx(32)
waitcnt(_clkfreq + cnt)
ser.stop
cogstop(0)
pub fib(i) : b | a
b := a := 1
repeat i
a := b + (b := a)

View file

@ -1,5 +1,5 @@
Public Function Fib(n As Integer) As Long
Dim fib0, fib1, sum As Long
Public Function Fib(ByVal n As Integer) As Variant
Dim fib0 As Variant, fib1 As Variant, sum As Variant
Dim i As Integer
fib0 = 0
fib1 = 1
@ -7,6 +7,6 @@ Public Function Fib(n As Integer) As Long
sum = fib0 + fib1
fib0 = fib1
fib1 = sum
Next
Next i
Fib = fib0
End Function

View file

@ -0,0 +1,56 @@
Imports System
Imports System.Collections.Generic
Imports System.Numerics
Module Module1
' A sparse array of values calculated along the way
Dim sl As SortedList(Of Integer, BigInteger) = New SortedList(Of Integer, BigInteger)()
' Square a BigInteger
Function sqr(ByVal n As BigInteger) As BigInteger
Return n * n
End Function
' Helper routine for Fsl(). It adds an entry to the sorted list when necessary
Sub IfNec(n as integer)
If Not sl.ContainsKey(n) Then sl.Add(n, Fsl(n))
End Sub
' 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
Function Fsl(ByVal n As Integer) As BigInteger
If n < 2 Then Return n
Dim n2 As Integer = n >> 1, pm As Integer = n2 + ((n And 1) << 1) - 1 : IfNec(n2) : IfNec(pm)
Return If(n2 > pm, (2 * sl(pm) + sl(n2)) * sl(n2), sqr(sl(n2)) + sqr(sl(pm)))
End Function
' Conventional iteration method (not used here)
Function Fm(ByVal n As BigInteger) As BigInteger
If n < 2 Then Return n
Dim cur As BigInteger = 0, pre As BigInteger = 1
For i As Integer = 0 To n - 1
Dim sum As BigInteger = cur + pre
pre = cur : cur = sum
Next : Return cur
End Function
Sub Main()
Dim num As Integer = 2_000_000
Dim st As DateTime = DateTime.Now
Dim v As BigInteger = Fsl(num)
Console.WriteLine("{0:n3} ms to calculate the {1:n0}th Fibonacci number,",
(DateTime.Now - st).TotalMilliseconds, num)
st = DateTime.Now
Dim vs As String = v.ToString()
Console.WriteLine("{0:n3} seconds to convert to a string.", (DateTime.Now - st).TotalSeconds)
Console.WriteLine("number of digits is {0}", vs.Length)
If vs.Length < 10000 Then
st = DateTime.Now
Console.WriteLine(vs)
Console.WriteLine("{0:n3} ms to write it to the console.", (DateTime.Now - st).TotalMilliseconds)
Else
Console.WriteLine("partial: {0}...{1}", vs.Substring(1, 35), vs.Substring(vs.Length - 35))
End If
End Sub
End Module

View file

@ -0,0 +1,14 @@
Function fibo(n As Integer) As UInt64
Dim noOne As UInt64 = 1
Dim noTwo As UInt64 = 1
Dim sum As UInt64
For i As Integer = 3 To n
sum = noOne + noTwo
noTwo = noOne
noOne = sum
Next
Return noOne
End Function