September 2017 Update

This commit is contained in:
Ingy döt Net 2017-09-23 10:01:46 +02:00
parent bba7bfd280
commit ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions

View file

@ -1,8 +1,8 @@
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>
<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:
@ -17,8 +17,9 @@ The sequence is sometimes extended into negative numbers by using a straightforw
support for negative &nbsp; &nbsp; <big> n </big> &nbsp; &nbsp; in the solution is optional.
;Related task:
;Related tasks:
* &nbsp; [[Fibonacci n-step number sequences]]
* &nbsp; [[Leonardo numbers]]
;References:

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

@ -1,19 +1,18 @@
-- fib :: Int -> Int
on fib(n)
-- (Int, Int) -> (Int, Int)
-- lastTwo : (Int, Int) -> (Int, Int)
script lastTwo
on lambda([a, b])
on |λ|([a, b])
[b, a + b]
end lambda
end |λ|
end script
item 1 of foldl(lastTwo, {0, 1}, range(1, n))
item 1 of foldl(lastTwo, {0, 1}, enumFromTo(1, n))
end fib
-- TEST
-- TEST -----------------------------------------------------------------------
on run
fib(32)
@ -21,9 +20,21 @@ on run
--> 2178309
end run
-- GENERIC FUNCTIONS ----------------------------------------------------------
-- GENERIC FUNCTIONS
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if n < m then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
@ -31,7 +42,7 @@ on foldl(f, startValue, xs)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to lambda(v, item i of xs, i, xs)
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
@ -44,21 +55,7 @@ on mReturn(f)
f
else
script
property lambda : f
property |λ| : f
end script
end if
end mReturn
-- range :: Int -> Int -> [Int]
on range(m, n)
if n < m then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end range

View file

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

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

@ -0,0 +1,2 @@
10 INPUT N
20 PRINT INT (0.5+(((SQR 5+1)/2)**N)/SQR 5)

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

@ -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,15 @@
stop = 6
a = 1
i = 1 # start
a # print result
fib
comefrom if i is 1 # start
b = 1
comefrom fib # start of loop
i = i + 1
next_b = a + b
a = b
b = next_b
comefrom fib if i > stop

View file

@ -1,21 +0,0 @@
(defconstant +2x2-identity+ '(1 0 0 1))
(defconstant +fib-seed+ '(1 1 1 0))
(defun multiply-2x2 (matrix-1 matrix-2)
(let* ((a (first matrix-1)) (b (second matrix-1)) (c (third matrix-1)) (d (fourth matrix-1))
(e (first matrix-2)) (f (second matrix-2)) (g (third matrix-2)) (h (fourth matrix-2))
(ae (* a e)) (bg (* b g)) (af (* a f)) (bh (* b h))
(ce (* c e)) (dg (* d g)) (cf (* c f)) (dh (* d h)))
(list (+ ae bg) (+ af bh) (+ ce dg) (+ cf dh))))
(defun square-2x2 (matrix)
(multiply-2x2 matrix matrix))
(defun 2x2-exponentiation (matrix n)
(cond ((zerop n) +2x2-identity+)
((eql n 1) matrix)
((evenp n) (square-2x2 (2x2-exponentiation matrix (/ n 2))))
(t (multiply-2x2 (square-2x2 (2x2-exponentiation matrix (/ (1- n) 2))) matrix))))
(defun fib (n)
(car (2x2-exponentiation +fib-seed+ (1- n))))

View file

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

View file

@ -1 +1,6 @@
[floor(0.01+(1/p**n+p**n)/sqrt 5)|let p=(1+sqrt 5)/2, n<-[0..42]]
main :: IO ()
main =
print
[ floor (0.01 + (1 / p ** n + p ** n) / sqrt 5)
| let p = (1 + sqrt 5) / 2
, n <- [0 .. 42] ]

View file

@ -1,15 +1,44 @@
import Data.List
import Data.List (transpose)
xs <+> ys = zipWith (+) xs ys
xs <*> ys = sum $ zipWith (*) xs ys
fib
:: (Integral b, Num a)
=> b -> a
fib 0 = 0 -- this line is necessary because "something ^ 0" returns "fromInteger 1", which unfortunately
-- in our case is not our multiplicative identity (the identity matrix) but just a 1x1 matrix of 1
fib n = (last . head . unMat) (Mat [[1, 1], [1, 0]] ^ n)
newtype Mat a = Mat {unMat :: [[a]]} deriving Eq
-- Code adapted from Matrix exponentiation operator task ---------------------
(<+>)
:: Num c
=> [c] -> [c] -> [c]
(<+>) = zipWith (+)
instance Show a => Show (Mat a) where
(<*>)
:: Num a
=> [a] -> [a] -> a
(<*>) = (sum .) . zipWith (*)
newtype Mat a = Mat
{ unMat :: [[a]]
} deriving (Eq)
instance Show a =>
Show (Mat a) where
show xm = "Mat " ++ show (unMat xm)
instance Num a => Num (Mat a) where
instance Num a =>
Num (Mat a) where
negate xm = Mat $ map (map negate) $ unMat xm
xm + ym = Mat $ zipWith (<+>) (unMat xm) (unMat ym)
xm * ym = Mat [[xs <*> ys | ys <- transpose $ unMat ym] | xs <- unMat xm]
xm + ym = Mat $ zipWith (<+>) (unMat xm) (unMat ym)
xm * ym =
Mat
[ [ xs Main.<*> ys -- to distinguish from standard applicative operator
| ys <- transpose $ unMat ym ]
| xs <- unMat xm ]
fromInteger n = Mat [[fromInteger n]]
abs = undefined
signum = undefined
-- TEST ----------------------------------------------------------------------
main :: IO ()
main = (print . take 10 . show . fib) (10 ^ 5)

View file

@ -1,3 +1,35 @@
fib 0 = 0 -- this line is necessary because "something ^ 0" returns "fromInteger 1", which unfortunately
-- in our case is not our multiplicative identity (the identity matrix) but just a 1x1 matrix of 1
fib n = last $ head $ unMat $ (Mat [[1,1],[1,0]]) ^ n
import Control.Arrow ((&&&))
fibstep :: (Integer, Integer) -> (Integer, Integer)
fibstep (a, b) = (b, a + b)
fibnums :: [Integer]
fibnums = map fst $ iterate fibstep (0, 1)
fibN2 :: Integer -> (Integer, Integer)
fibN2 m
| m < 10 = iterate fibstep (0, 1) !! fromIntegral m
fibN2 m = fibN2_next (n, r) (fibN2 n)
where
(n, r) = quotRem m 3
fibN2_next (n, r) (f, g)
| r == 0 = (a, b) -- 3n ,3n+1
| r == 1 = (b, c) -- 3n+1,3n+2
| r == 2 = (c, d) -- 3n+2,3n+3 (*)
where
a =
5 * f ^ 3 +
if even n
then 3 * f
else (-3 * f) -- 3n
b = g ^ 3 + 3 * g * f ^ 2 - f ^ 3 -- 3n+1
c = g ^ 3 + 3 * g ^ 2 * f + f ^ 3 -- 3n+2
d =
5 * g ^ 3 +
if even n
then (-3 * g)
else 3 * g -- 3(n+1) (*)
main :: IO ()
main = print $ (length &&& take 20) . show . fst $ fibN2 (10 ^ 2)

View file

@ -1,20 +1,2 @@
fibsteps (a,b) n
| n <= 0 = (a,b)
| otherwise = fibsteps (b, a+b) (n-1)
fibnums :: [Integer]
fibnums = map fst $ iterate (`fibsteps` 1) (0,1)
fibN2 :: Integer -> (Integer, Integer)
fibN2 m | m < 10 = fibsteps (0,1) m
fibN2 m = fibN2_next (n,r) (fibN2 n)
where (n,r) = quotRem m 3
fibN2_next (n,r) (f,g) | r==0 = (a,b) -- 3n ,3n+1
| r==1 = (b,c) -- 3n+1,3n+2
| r==2 = (c,d) -- 3n+2,3n+3 (*)
where
a = ( 5*f^3 + if even n then 3*f else (- 3*f) ) -- 3n
b = ( g^3 + 3 * g * f^2 - f^3 ) -- 3n+1
c = ( g^3 + 3 * g^2 * f + f^3 ) -- 3n+2
d = ( 5*g^3 + if even n then (- 3*g) else 3*g ) -- 3(n+1) (*)
*Main> (length &&& take 20) . show . fst $ fibN2 (10^6)
(208988,"19532821287077577316")

View file

@ -1,2 +1 @@
*Main> take 10 $ show $ fst $ fibN2 (10^6)
"1953282128"
f (n,(a,b)) = (2*n,(a*a+b*b,2*a*b+b*b)) -- iterate f (1,(0,1)) ; b is nth

View file

@ -0,0 +1 @@
g (n,(a,b)) = (2*n,(2*a*b-a*a,a*a+b*b)) -- iterate g (1,(1,1)) ; a is nth

View file

@ -1 +1,6 @@
fib x = if x < 1 then 0 else if x < 2 then 1 else fib(x - 1) + fib(x - 2)
fib x =
if x < 1
then 0
else if x < 2
then 1
else fib (x - 1) + fib (x - 2)

View file

@ -1,5 +1,8 @@
fib x = if x < 1 then 0
else if x==1 then 1
else fibs!!(x - 1) + fibs!!(x - 2)
fib x =
if x < 1
then 0
else if x == 1
then 1
else fibs !! (x - 1) + fibs !! (x - 2)
where
fibs = map fib [0..]
fibs = map fib [0 ..]

View file

@ -1,2 +1,5 @@
fib :: Integer -> Integer
fib n = fst $ foldl (\(a, b) _ -> (b, a + b)) (0, 1) [1 .. n]
fib n = go n 0 1
where
go n a b
| n == 0 = a
| otherwise = go (n - 1) b (a + b)

View file

@ -1,4 +1 @@
fib n = go n 0 1
where
go n a b | n==0 = a
| otherwise = go (n-1) b (a+b)
fib = 0 : 1 : zipWith (+) fib (tail fib)

View file

@ -1 +1 @@
fib = 0 : 1 : zipWith (+) fib (tail fib)
fib = 0 : 1 : (zipWith (+) <*> tail) fib

View file

@ -1 +1 @@
fib = 0 : 1 : (zipWith (+) <*> tail) fib
fib = 0 : 1 : next fib where next (a: t@(b:_)) = (a+b) : next t

View file

@ -1 +1 @@
fib = 0 : 1 : next fib where next (a: t@(b:_)) = (a+b) : next t
fib = 0 : scanl (+) 1 fib

View file

@ -1 +1,9 @@
fib = 0 : scanl (+) 1 fib
import Data.List (foldl') --'
fib :: Integer -> Integer
fib n =
fst $
foldl' --'
(\(a, b) _ -> (b, a + b))
(0, 1)
[1 .. n]

View file

@ -1,5 +1,3 @@
function fib(n) {
return function(n,a,b) {
return n>0 ? arguments.callee(n-1,b,a+b) : a;
}(n,0,1);
return n<2?n:fib(n-1)+fib(n-2);
}

View file

@ -0,0 +1,22 @@
(() => {
'use strict';
// fib :: Int -> Int
let fib = n => range(1, n)
.reduce(([a, b]) => [b, a + b], [0, 1])[0];
// GENERIC [m..n]
// range :: Int -> Int -> [Int]
let range = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// TEST
return fib(32);
// --> 2178309
})();

View file

@ -1,10 +1,3 @@
function fib(n) {
var a = 0, b = 1, t;
while (n-- > 0) {
t = a;
a = b;
b += t;
console.log(a);
}
return a;
if (n<2) { return n; } else { return fib(n-1)+fib(n-2); }
}

View file

@ -1,7 +1,5 @@
var fib = (function(cache){
return cache = cache || {}, function(n){
if (cache[n]) return cache[n];
else return cache[n] = n == 0 ? 0 : n < 0 ? -fib(-n)
: n <= 2 ? 1 : fib(n-2) + fib(n-1);
};
})();
function fib(n) {
return function(n,a,b) {
return n>0 ? arguments.callee(n-1,b,a+b) : a;
}(n,0,1);
}

View file

@ -1,17 +1,10 @@
(function () {
'use strict';
function fib(n) {
return Array.apply(null, Array(n + 1))
.map(function (_, i, lst) {
return lst[i] = (
i ? i < 2 ? 1 :
lst[i - 2] + lst[i - 1] :
0
);
})[n];
}
return fib(32);
})();
function fib(n) {
var a = 0, b = 1, t;
while (n-- > 0) {
t = a;
a = b;
b += t;
console.log(a);
}
return a;
}

View file

@ -1,17 +1,7 @@
function Y(dn) {
return (function(fn) {
return fn(fn);
}(function(fn) {
return dn(function() {
return fn(fn).apply(null, arguments);
});
}));
}
var fib = Y(function(fn) {
return function(n) {
if (n === 0 || n === 1) {
return n;
}
return fn(n - 1) + fn(n - 2);
var fib = (function(cache){
return cache = cache || {}, function(n){
if (cache[n]) return cache[n];
else return cache[n] = n == 0 ? 0 : n < 0 ? -fib(-n)
: n <= 2 ? 1 : fib(n-2) + fib(n-1);
};
});
})();

View file

@ -1,10 +1,17 @@
function* fibonacciGenerator() {
var prev = 0;
var curr = 1;
while (true) {
yield curr;
curr = curr + prev;
prev = curr - prev;
(function () {
'use strict';
function fib(n) {
return Array.apply(null, Array(n + 1))
.map(function (_, i, lst) {
return lst[i] = (
i ? i < 2 ? 1 :
lst[i - 2] + lst[i - 1] :
0
);
})[n];
}
}
var fib = fibonacciGenerator();
return fib(32);
})();

View file

@ -1,35 +1,17 @@
(() => {
'use strict';
// Nth member of fibonacci series
// fib :: Int -> Int
function fib(n) {
return mapAccumL(([a, b]) => [
[b, a + b], b
], [0, 1], range(1, n))[0][0];
function Y(dn) {
return (function(fn) {
return fn(fn);
}(function(fn) {
return dn(function() {
return fn(fn).apply(null, arguments);
});
}));
}
var fib = Y(function(fn) {
return function(n) {
if (n === 0 || n === 1) {
return n;
}
return fn(n - 1) + fn(n - 2);
};
// GENERIC FUNCTIONS
// mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
let mapAccumL = (f, acc, xs) => {
return xs.reduce((a, x) => {
let pair = f(a[0], x);
return [pair[0], a[1].concat(pair[1])];
}, [acc, []]);
}
// range :: Int -> Int -> Maybe Int -> [Int]
let range = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// TEST
return fib(32);
// --> 2178309
})();
});

View file

@ -1,22 +1,10 @@
(() => {
'use strict';
// fib :: Int -> Int
let fib = n => range(1, n)
.reduce(([a, b]) => [b, a + b], [0, 1])[0];
// GENERIC [m..n]
// range :: Int -> Int -> [Int]
let range = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// TEST
return fib(32);
// --> 2178309
})();
function* fibonacciGenerator() {
var prev = 0;
var curr = 1;
while (true) {
yield curr;
curr = curr + prev;
prev = curr - prev;
}
}
var fib = fibonacciGenerator();

View file

@ -0,0 +1,35 @@
(() => {
'use strict';
// Nth member of fibonacci series
// fib :: Int -> Int
function fib(n) {
return mapAccumL(([a, b]) => [
[b, a + b], b
], [0, 1], range(1, n))[0][0];
};
// GENERIC FUNCTIONS
// mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
let mapAccumL = (f, acc, xs) => {
return xs.reduce((a, x) => {
let pair = f(a[0], x);
return [pair[0], a[1].concat(pair[1])];
}, [acc, []]);
}
// range :: Int -> Int -> Maybe Int -> [Int]
let range = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// TEST
return fib(32);
// --> 2178309
})();

View file

@ -1,12 +1,10 @@
package fibonacci
enum class Fibonacci {
ITERATIVE {
override fun invoke(n: Long) = if (n < 2 )
override fun invoke(n: Long) = if (n < 2) {
n
else {
var n1: Long = 0
var n2: Long = 1
} else {
var n1 = 0L
var n2 = 1L
var i = n
do {
val sum = n1 + n2

View file

@ -0,0 +1,16 @@
HAI 1.2
HOW DUZ I fibonacci YR N
EITHER OF BOTH SAEM N AN 1 AN BOTH SAEM N AN 0
O RLY?
YA RLY, FOUND YR 1
NO WAI
I HAS A N1
I HAS A N2
N1 R DIFF OF N AN 1
N2 R DIFF OF N AN 2
N1 R fibonacci N1
N2 R fibonacci N2
FOUND YR SUM OF N1 AN N2
OIC
IF U SAY SO
KTHXBYE

View file

@ -1,5 +0,0 @@
proc Fibonacci(n: int): int64 =
var fn = float64(n)
var p: float64 = (1.0 + sqrt(5.0)) / 2.0
var q: float64 = 1.0 / p
return int64((pow(p, fn) + pow(q, fn)) / sqrt(5.0))

View file

@ -1,10 +0,0 @@
proc Fibonacci(n: int): int =
var
first = 0
second = 1
for i in 0 .. <n:
swap first, second
second += first
result = first

View file

@ -1,5 +0,0 @@
proc Fibonacci(n: int): int64 =
if n <= 2:
result = 1
else:
result = Fibonacci(n - 1) + Fibonacci(n - 2)

View file

@ -1,7 +0,0 @@
proc Fibonacci(n: int, current: int64, next: int64): int64 =
if n == 0:
result = current
else:
result = Fibonacci(n - 1, next, current + next)
proc Fibonacci(n: int): int64 =
result = Fibonacci(n, 0, 1)

View file

@ -1,11 +0,0 @@
iterator fib: int {.closure.} =
var a = 0
var b = 1
while true:
yield a
swap a, b
b = a + b
var f = fib
for i in 0.. <10:
echo f()

View file

@ -1,12 +1,19 @@
let rec fib_rec n =
if n < 2 then
n
else
fib_rec (n - 1) + fib_rec (n - 2)
open Num
(* with support for negatives *)
let rec fib = function
0 -> 0
| 1 -> 1
| n -> if n > 0 then fib (n-1) + fib (n-2)
else fib (n+2) - fib (n+1)
let fib =
let rec fib_aux f0 f1 = function
| 0 -> f0
| 1 -> f1
| n -> fib_aux f1 (f1 +/ f0) (n - 1)
in
fib_aux (num_of_int 0) (num_of_int 1)
(* support for negatives *)
let fib n =
if n < 0 && n mod 2 = 0 then minus_num (fib (abs n))
else fib (abs n)
;;
(* It can be called from the command line with an argument *)
(* Result is send to standart output *)
let n = int_of_string Sys.argv.(1) in
print_endline (string_of_num (fib n))

View file

@ -1,12 +1,16 @@
let fib n =
let rec fib_aux n a b =
match n with
| 0 -> a
| _ -> fib_aux (n-1) b (a+b)
in
fib_aux n 0 1
open Num
let mul (a,b,c) (d,e,f) = let bxe = b*/e in
(a*/d +/ bxe, a*/e +/ b*/f, bxe +/ c*/f)
let id = (Int 1, Int 0, Int 1)
let rec pow a n =
if n=0 then id else
let b = pow a (n/2) in
if (n mod 2) = 0 then mul b b else mul a (mul b b)
(* support for negatives *)
let fib n =
if n < 0 && n mod 2 = 0 then -fib (abs n)
else fib (abs n)
let (_,y,_) = (pow (Int 1, Int 1, Int 0) n) in
string_of_num y
;;
Printf.printf "fib %d = %s\n" 300 (fib 300)

View file

@ -1,19 +0,0 @@
open Num
let fib =
let rec fib_aux f0 f1 = function
| 0 -> f0
| 1 -> f1
| n -> fib_aux f1 (f1 +/ f0) (n - 1)
in
fib_aux (num_of_int 0) (num_of_int 1)
(* support for negatives *)
let fib n =
if n < 0 && n mod 2 = 0 then minus_num (fib (abs n))
else fib (abs n)
;;
(* It can be called from the command line with an argument *)
(* Result is send to standart output *)
let n = int_of_string Sys.argv.(1) in
print_endline (string_of_num (fib n))

View file

@ -1,16 +0,0 @@
open Num
let mul (a,b,c) (d,e,f) = let bxe = b*/e in
(a*/d +/ bxe, a*/e +/ b*/f, bxe +/ c*/f)
let id = (Int 1, Int 0, Int 1)
let rec pow a n =
if n=0 then id else
let b = pow a (n/2) in
if (n mod 2) = 0 then mul b b else mul a (mul b b)
let fib n =
let (_,y,_) = (pow (Int 1, Int 1, Int 0) n) in
string_of_num y
;;
Printf.printf "fib %d = %s\n" 300 (fib 300)

View file

@ -1,18 +1,16 @@
sequence fcache = {1,1}
function fibonamem(integer n) -- memoized, works for -ve numbers, inaccurate above 78
integer absn = abs(n)
function fibonacci(integer n) -- iterative, works for -ve numbers
atom a=0, b=1
if n=0 then return 0 end if
if absn>length(fcache) then
fcache = append(fcache,fibonamem(absn-1)+fibonamem(absn-2))
if absn!=length(fcache) then ?9/0 end if
end if
if abs(n)>=79 then ?9/0 end if -- inaccuracies creep in above 78
for i=1 to abs(n)-1 do
{a,b} = {b,a+b}
end for
if n<0 and remainder(n,2)=0 then return -fcache[absn] end if
return fcache[absn]
end function
for i=0 to 30 do
printf(1,"%d", fibonamem(i))
if i!=30 then puts(1,", ") end if
for i=0 to 28 do
if i then puts(1,", ") end if
printf(1,"%d", fibonacci(i))
end for
puts(1,"\n")

View file

@ -5,18 +5,17 @@ sequence fcacheba = {BA_ONE,BA_ONE}
function fibonamemba(integer n) -- memoized, works for -ve numbers, yields bigatom
integer absn = abs(n)
if n=0 then return BA_ZERO end if
if absn>length(fcacheba) then
fcacheba = append(fcacheba,ba_add(fibonamemba(absn-1),fibonamemba(absn-2)))
if absn!=length(fcacheba) then ?9/0 end if
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]
end function
for i=0 to 30 do
for i=0 to 28 do
if i then puts(1,", ") end if
ba_printf(1,"%B", fibonamemba(i))
if i!=30 then puts(1,", ") end if
end for
puts(1,"\n")
ba_printf(1,"%B", fibonamemba(777))
ba_printf(1,"%B", fibonamemba(705))
puts(1,"\n")

View file

@ -1,10 +1,5 @@
from math import *
def fib(n,x=[0,1]):
for i in range(abs(n)-1): x=[x[1],sum(x)]
return x[1]*pow(-1,abs(n)-1) if n<0 else x[1] if n else 0
def analytic_fibonacci(n):
sqrt_5 = sqrt(5);
p = (1 + sqrt_5) / 2;
q = 1/p;
return int( (p**n + q**n) / sqrt_5 + 0.5 )
for i in range(1,31):
print analytic_fibonacci(i),
for i in range(-30,31): print fib(i),

View file

@ -1,10 +1,7 @@
def fib():
"""Yield fib[n+1] + fib[n]"""
yield 1 # have to start somewhere
lhs, rhs = fib(), fib()
yield next(lhs) # move lhs one iteration ahead
while True:
yield next(lhs)+next(rhs)
def fib(n, c={0:1, 1:1}):
if n not in c:
x = n // 2
c[n] = fib(x-1) * fib(n-x-1) + fib(x) * fib(n - x)
return c[n]
f=fib()
print [next(f) for _ in range(9)]
fib(10000000) # calculating it takes a few seconds, printing it takes eons

View file

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

View file

@ -0,0 +1,11 @@
from itertools import islice
def fib():
yield 0
yield 1
a, b = fib(), fib()
next(b)
while True:
yield next(a)+next(b)
print(tuple(islice(fib(), 10)))

View file

@ -1,8 +1,10 @@
def fibIter(n):
if n < 2:
return n
fibPrev = 1
fib = 1
for num in xrange(2, n):
fibPrev, fib = fib, fib + fibPrev
return fib
from math import *
def analytic_fibonacci(n):
sqrt_5 = sqrt(5);
p = (1 + sqrt_5) / 2;
q = 1/p;
return int( (p**n + q**n) / sqrt_5 + 0.5 )
for i in range(1,31):
print analytic_fibonacci(i),

View file

@ -1,5 +1,8 @@
def fibRec(n):
def fibIter(n):
if n < 2:
return n
else:
return fibRec(n-1) + fibRec(n-2)
fibPrev = 1
fib = 1
for num in xrange(2, n):
fibPrev, fib = fib, fib + fibPrev
return fib

View file

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

View file

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

View file

@ -1,5 +1,7 @@
def fibGen(n):
a, b = 0, 1
while n>0:
yield a
a, b, n = b, a+b, n-1
def fibFastRec(n):
def fib(prvprv, prv, c):
if c < 1:
return prvprv
else:
return fib(prv, prvprv + prv, c - 1)
return fib(0, 1, n)

View file

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

View file

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

View file

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

View file

@ -0,0 +1,6 @@
fib=function(n,x=c(0,1)) {
if (abs(n)>1) for (i in seq(abs(n)-1)) x=c(x[2],sum(x))
if (n<0) return(x[2]*(-1)^(abs(n)-1)) else if (n) return(x[2]) else return(0)
}
sapply(seq(-31,31),fib)

View file

@ -1,11 +1,7 @@
require 'generator'
def fib_gen
Generator.new do |g|
f0, f1 = 0, 1
loop do
g.yield f0
f0, f1 = f1, f0 + f1
end
end
fib = Enumerator.new do |y|
f0, f1 = 0, 1
loop do
y << f0
f0, f1 = f1, f0 + f1
end
end

View file

@ -6,9 +6,9 @@ fn main() {
}
}
fn fibonacci_gen(terms: i32) -> impl Iterator<Item=f64> {
fn fibonacci_gen(terms: i32) -> impl Iterator<Item=u64> {
let sqrt_5 = 5.0f64.sqrt();
let p = (1.0 +sqrt_5) / 2.0;
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).floor())
(1..terms).map(move |n| ((p.powi(n) + q.powi(n)) / sqrt_5 + 0.5) as u64)
}

View file

@ -0,0 +1,4 @@
fibo(n)=
s5 = #.sqrt(5)
<= (((1+s5)/2)^n-((1-s5)/2)^n)/s5
.

View file

@ -0,0 +1,11 @@
fibo(n)=
? n<2, <= n
f2 = 0
f1 = 1
> i, 2..n
f = f1+f2
f2 = f1
f1 = f
<
<= f
.

View file

@ -0,0 +1,4 @@
fibo(n)=
? n<2, <= n
<= fibo(n-1)+fibo(n-2)
.

View file

@ -1,27 +1,16 @@
CREATE FUNCTION fib(n int) RETURNS numeric AS $$
-- This recursive with generates endless list of Fibonacci numbers.
WITH RECURSIVE fibonacci(current, previous) AS (
-- Initialize the current with 0, so the first value will be 0.
-- The previous value is set to 1, because its only goal is not
-- special casing the zero case, and providing 1 as the second
-- number in the sequence.
--
-- The numbers end with dots to make them numeric type in
-- Postgres. Numeric type has almost arbitrary precision
-- (technically just 131,072 digits, but that's good enough for
-- most purposes, including calculating huge Fibonacci numbers)
SELECT 0., 1.
UNION ALL
-- To generate Fibonacci number, we need to add together two
-- previous Fibonacci numbers. Current number is saved in order
-- to be accessed in the next iteration of recursive function.
SELECT previous + current, current FROM fibonacci
)
-- The user is only interested in current number, not previous.
SELECT current FROM fibonacci
-- We only need one number, so limit to 1
LIMIT 1
-- Offset the query by the requested argument to get the correct
-- position in the list.
OFFSET n
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT IMMUTABLE;
SQL> with fib(e,f) as (select 1, 1 from dual union all select e+f,e from fib where e <= 55) select f from fib;
F
----------
1
1
2
3
5
8
13
21
34
55
10 rows selected.

View file

@ -0,0 +1,27 @@
CREATE FUNCTION fib(n int) RETURNS numeric AS $$
-- This recursive with generates endless list of Fibonacci numbers.
WITH RECURSIVE fibonacci(current, previous) AS (
-- Initialize the current with 0, so the first value will be 0.
-- The previous value is set to 1, because its only goal is not
-- special casing the zero case, and providing 1 as the second
-- number in the sequence.
--
-- The numbers end with dots to make them numeric type in
-- Postgres. Numeric type has almost arbitrary precision
-- (technically just 131,072 digits, but that's good enough for
-- most purposes, including calculating huge Fibonacci numbers)
SELECT 0., 1.
UNION ALL
-- To generate Fibonacci number, we need to add together two
-- previous Fibonacci numbers. Current number is saved in order
-- to be accessed in the next iteration of recursive function.
SELECT previous + current, current FROM fibonacci
)
-- The user is only interested in current number, not previous.
SELECT current FROM fibonacci
-- We only need one number, so limit to 1
LIMIT 1
-- Offset the query by the requested argument to get the correct
-- position in the list.
OFFSET n
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT IMMUTABLE;

View file

@ -0,0 +1,40 @@
#!/bin/sed -f
# First we need to convert each number into the right number of ticks
# Start by marking digits
s/[0-9]/<&/g
# We have to do the digits manually.
s/0//g; s/1/|/g; s/2/||/g; s/3/|||/g; s/4/||||/g; s/5/|||||/g
s/6/||||||/g; s/7/|||||||/g; s/8/||||||||/g; s/9/|||||||||/g
# Multiply by ten for each digit from the front.
:tens
s/|</<||||||||||/g
t tens
# Done with digit markers
s/<//g
# Now the actual work.
:split
# Convert each stretch of n >= 2 ticks into two of n-1, with a mark between
s/|\(|\+\)/\1-\1/g
# Convert the previous mark and the first tick after it to a different mark
# giving us n-1+n-2 marks.
s/-|/+/g
# Jump back unless we're done.
t split
# Get rid of the pluses, we're done with them.
s/+//g
# Convert back to digits
:back
s/||||||||||/</g
s/<\([0-9]*\)$/<0\1/g
s/|||||||||/9/g;
s/|||||||||/9/g; s/||||||||/8/g; s/|||||||/7/g; s/||||||/6/g;
s/|||||/5/g; s/||||/4/g; s/|||/3/g; s/||/2/g; s/|/1/g;
s/</|/g
t back
s/^$/0/

View file

@ -1,7 +1,5 @@
func fib_iter(n) {
var fib = [1, 1];
(n - fib.len).times {
fib = [fib[-1], fib[-2] + fib[-1]]
};
fib[-1];
var (a, b) = (0, 1)
{ (a, b) = (b, a+b) } * n
return a
}

View file

@ -1,3 +1,3 @@
func fib_rec(n) {
n < 2 ? n : (__FUNC__(n-1) + __FUNC__(n-2));
n < 2 ? n : (__FUNC__(n-1) + __FUNC__(n-2))
}

View file

@ -1,3 +1,3 @@
func fib_mem (n) is cached {
n < 2 ? n : (__FUNC__(n-1) + __FUNC__(n-2));
n < 2 ? n : (__FUNC__(n-1) + __FUNC__(n-2))
}

View file

@ -1,5 +1,5 @@
func fib_closed(n) {
define S = (1.25.sqrt + 0.5);
define T = (-S + 1);
(S**n - T**n) / (-T + S) -> roundf(0);
define S = (1.25.sqrt + 0.5)
define T = (-S + 1)
(S**n - T**n) / (-T + S) -> round
}

View file

@ -0,0 +1 @@
say fib(12) #=> 144

View file

@ -0,0 +1,31 @@
FOR i = 0 TO 15
PRINT fibR(i),fibI(i),fibN(i)
NEXT i
/* Recursive Method */
DEF fibR(n)
IF n <= 1 THEN
fibR = n
ELSE
fibR = fibR(n-1) + fibR(n-2)
ENDIF
END DEF
/* Iterative Method */
DEF fibI(n)
a = 0
b = 1
FOR i = 1 TO n
temp = a + b
a = b
b = temp
NEXT i
fibI = a
END DEF
/* N-th Term Method */
DEF fibN(n)
uphi = .5 + SQR(5)/2
lphi = .5 - SQR(5)/2
fibN = (uphi^n-lphi^n)/SQR(5)
END DEF

View file

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

View file

@ -0,0 +1,12 @@
. mata
: function fib(n) {
return((((1+sqrt(5))/2):^n-((1-sqrt(5))/2):^n)/sqrt(5))
}
: fib(0..10)
1 2 3 4 5 6 7 8 9 10 11
+--------------------------------------------------------+
1 | 0 1 1 2 3 5 8 13 21 34 55 |
+--------------------------------------------------------+
: end

View file

@ -1,3 +0,0 @@
:Prompt N
:.5(1+√(5))→P
:(P^N(-1/P)^N)/√(5)

View file

@ -1,5 +1,5 @@
def (fib n saved)
# all args in wart are optional, and we expect callers to not provide saved
# all args in Wart are optional, and we expect callers to not provide `saved`
default saved :to (table 0 0 1 1) # pre-populate base cases
default saved.n :to
(+ (fib n-1 saved) (fib n-2 saved))

View file

@ -0,0 +1,51 @@
TITLE i hate visual studio 4 (Fibs.asm)
; __ __/--------\
; >__ \ / | |\
; \ \___/ @ \ / \__________________
; \____ \ / \\\
; \____ Coded with love by: |||
; \ Alexander Alvonellos |||
; | 9/29/2011 / ||
; | | MM
; | |--------------| |
; |< | |< |
; | | | |
; |mmmmmm| |mmmmm|
;; Epic Win.
INCLUDE Irvine32.inc
.data
BEERCOUNT = 48;
Fibs dd 0, 1, BEERCOUNT DUP(0);
.code
main PROC
; I am not responsible for this code.
; They made me write it, against my will.
;Here be dragons
mov esi, offset Fibs; offset array; ;;were to start (start)
mov ecx, BEERCOUNT; ;;count of items (how many)
mov ebx, 4; ;;size (in number of bytes)
call DumpMem;
mov ecx, BEERCOUNT; ;//http://www.wolframalpha.com/input/?i=F ib%5B47%5D+%3E+4294967295
mov esi, offset Fibs
NextPlease:;
mov eax, [esi]; ;//Get me the data from location at ESI
add eax, [esi+4]; ;//add into the eax the data at esi + another double (next mem loc)
mov [esi+8], eax; ;//Move that data into the memory location after the second number
add esi, 4; ;//Update the pointer
loop NextPlease; ;//Thank you sir, may I have another?
;Here be dragons
mov esi, offset Fibs; offset array; ;;were to start (start)
mov ecx, BEERCOUNT; ;;count of items (how many)
mov ebx, 4; ;;size (in number of bytes)
call DumpMem;
exit ; exit to operating system
main ENDP
END main

View file

@ -0,0 +1,7 @@
h#1 h#1 h#1 o#
h#10 o$ p
>f
o# h#10 o$ p
ma h? jnext p
t
jnf

View file

@ -0,0 +1,8 @@
(defun fibonacci (x)
(defun fib (a b n)
(if (= n 2)
b
(fib b (+ a b) (- n 1)) ) )
(if (< x 2)
x
(fib 1 1 x) ) )

View file

@ -0,0 +1 @@
10 DEF FN f(x)=INT (0.5+(((SQR 5+1)/2)^x)/SQR 5)

View file

@ -0,0 +1 @@
var fibShift=fcn(ab){ab.append(ab.sum()).pop(0)}.fp(L(0,1));