2016 Update

This commit is contained in:
Tina Müller 2016-12-05 22:15:40 +01:00
parent 948b86eafa
commit dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions

View file

@ -1,24 +1,31 @@
The '''Fibonacci sequence''' is a sequence F<sub>n</sub> of natural numbers defined recursively:
F<sub>0</sub> = 0
F<sub>1</sub> = 1
F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub>, if n>1
The '''Fibonacci sequence''' is a sequence &nbsp; <big> F<sub>n</sub> </big> &nbsp; of natural numbers defined recursively:
<big><big> F<sub>0</sub> = 0 </big></big>
<big><big> F<sub>1</sub> = 1 </big></big>
<big><big> F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub>, if n>1 </big></big>
;Task:
Write a function to generate the &nbsp; <big> n<sup>th</sup> </big> &nbsp; Fibonacci number.
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
F<sub>n</sub> = F<sub>n+2</sub> - F<sub>n+1</sub>, if n<0
<big><big> F<sub>n</sub> = F<sub>n+2</sub> - F<sub>n+1</sub>, if n<0 </big></big>
Support for negative n in the solution is optional.
support for negative &nbsp; &nbsp; <big> n </big> &nbsp; &nbsp; in the solution is optional.
;Related task:
* &nbsp; [[Fibonacci n-step number sequences]]
;Cf.:
* [[Fibonacci n-step number sequences]]
;References:
* [[wp:Fibonacci number|Wikipedia, Fibonacci number]]
* [[wp:Lucas number|Wikipedia, Lucas number]]
* [http://mathworld.wolfram.com/FibonacciNumber.html MathWorld, Fibonacci Number]
* [http://www.math-cs.ucmo.edu/~curtisc/articles/howardcooper/genfib4.pdf Some identities for r-Fibonacci numbers]
*[[oeis:A000045|OEIS Fibonacci numbers]]
*[[oeis:A000032|OEIS Lucas numbers]]
* &nbsp; [[wp:Fibonacci number|Wikipedia, Fibonacci number]]
* &nbsp; [[wp:Lucas number|Wikipedia, Lucas number]]
* &nbsp; [http://mathworld.wolfram.com/FibonacciNumber.html MathWorld, Fibonacci Number]
* &nbsp; [http://www.math-cs.ucmo.edu/~curtisc/articles/howardcooper/genfib4.pdf Some identities for r-Fibonacci numbers]
* &nbsp; [[oeis:A000045|OEIS Fibonacci numbers]]
* &nbsp; [[oeis:A000032|OEIS Lucas numbers]]
<br><br>

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,9 @@
on fib(n)
if n < 1 then
0
else if n < 3 then
1
else
fib(n - 2) + fib(n - 1)
end if
end fib

View file

@ -0,0 +1,64 @@
-- fib :: Int -> Int
on fib(n)
-- (Int, Int) -> (Int, Int)
script lastTwo
on lambda([a, b])
[b, a + b]
end lambda
end script
item 1 of foldl(lastTwo, {0, 1}, range(1, n))
end fib
-- TEST
on run
fib(32)
--> 2178309
end run
-- GENERIC FUNCTIONS
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to lambda(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property lambda : 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 @@
fib { <- 0 1 { dup <- + -> swap } -> times zap } <

View file

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

View file

@ -1,20 +0,0 @@
((main
{{iter fib !}
20 times
collect !
rev
{%d " " . <<}
each})
(collect { -1 take })
(fib
{{dup 2 <}
{fnord}
{dup
<- 2 - fib ! ->
1 - fib !
+ }
ifte}))

View file

@ -1,3 +1,3 @@
long long int fibb(long long int a, long long int b, int n) {
return (--n>0)?(fibb(b, a+b, n)):(a);
long long fibb(long long a, long long b, int n) {
return (--n>0)?(fibb(b, a+b, n)):(a);
}

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

@ -0,0 +1,15 @@
func fib(c chan int) {
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)
}
}

View file

@ -1,2 +1,8 @@
def rFib
rFib = { it < 1 ? 0 : it == 1 ? 1 : rFib(it-1) + rFib(it-2) }
rFib = {
it == 0 ? 0
: it == 1 ? 1
: it > 1 ? rFib(it-1) + rFib(it-2)
/*it < 0*/: rFib(it+2) - rFib(it+1)
}

View file

@ -1 +1,6 @@
def iFib = { it < 1 ? 0 : it == 1 ? 1 : (2..it).inject([0,1]){i, j -> [i[1], i[0]+i[1]]}[1] }
def iFib = {
it == 0 ? 0
: it == 1 ? 1
: it > 1 ? (2..it).inject([0,1]){i, j -> [i[1], i[0]+i[1]]}[1]
/*it < 0*/: (-1..it).inject([0,1]){i, j -> [i[1]-i[0], i[0]]}[0]
}

View file

@ -1 +1,2 @@
(0..20).each { println "${it}: ${rFib(it)} ${iFib(it)}" }
final φ = (1 + 5**(1/2))/2
def aFib = { (φ**it - (-φ)**(-it))/(5**(1/2)) as BigInteger }

View file

@ -0,0 +1,16 @@
def time = { Closure c ->
def start = System.currentTimeMillis()
def result = c()
def elapsedMS = (System.currentTimeMillis() - start)/1000
printf '(%6.4fs elapsed)', elapsedMS
result
}
print " F(n) elapsed time "; (-10..10).each { printf ' %3d', it }; println()
print "--------- -----------------"; (-10..10).each { print ' ---' }; println()
[recursive:rFib, iterative:iFib, analytic:aFib].each { name, fib ->
printf "%9s ", name
def fibList = time { (-10..10).collect {fib(it)} }
fibList.each { printf ' %3d', it }
println()
}

View file

@ -1 +1 @@
fib = 0 : 1 : zipWith (+) fib (tail fib)
[floor(0.01+(1/p**n+p**n)/sqrt 5)|let p=(1+sqrt 5)/2, n<-[0..42]]

View file

@ -0,0 +1,15 @@
import Data.List
xs <+> ys = zipWith (+) xs ys
xs <*> ys = sum $ zipWith (*) xs ys
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
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]
fromInteger n = Mat [[fromInteger n]]

View file

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

View file

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

View file

@ -0,0 +1,2 @@
*Main> take 10 $ show $ fst $ fibN2 (10^6)
"1953282128"

View file

@ -1 +1 @@
fib = 0 : 1 : next fib where next (a: t@(b:_)) = (a+b) : next t
fib x = if x < 1 then 0 else if x < 2 then 1 else fib(x - 1) + fib(x - 2)

View file

@ -1 +1,5 @@
fib = 0 : scanl (+) 1 fib
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..]

View file

@ -1,15 +1,2 @@
import Data.List
xs <+> ys = zipWith (+) xs ys
xs <*> ys = sum $ zipWith (*) xs ys
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
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]
fromInteger n = Mat [[fromInteger n]]
fib :: Integer -> Integer
fib n = fst $ foldl (\(a, b) _ -> (b, a + b)) (0, 1) [1 .. n]

View file

@ -1,3 +1,4 @@
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
fib n = go n 0 1
where
go n a b | n==0 = a
| otherwise = go (n-1) b (a+b)

View file

@ -1,20 +1 @@
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
d = ( 5*g^3 + if even n then (- 3*g) else 3*g ) -- 3(n+1) (*)
b = ( g^3 + 3 * g * f^2 - f^3 ) -- 3n+1
c = ( g^3 + 3 * g^2 * f + f^3 ) -- 3n+2
fib = 0 : 1 : zipWith (+) fib (tail fib)

View file

@ -1,2 +1 @@
*Main> take 10 $ show $ fst $ fibN2 (10^6)
"1953282128"
fib = 0 : 1 : (zipWith (+) <*> tail) fib

View file

@ -1 +1 @@
let fib x = if x < 1 then 0 else (if x < 3 then 1 else (fib(x - 1) + fib(x - 2)))
fib = 0 : 1 : next fib where next (a: t@(b:_)) = (a+b) : next t

View file

@ -0,0 +1 @@
fib = 0 : scanl (+) 1 fib

View file

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

View file

@ -0,0 +1,18 @@
import java.util.function.LongUnaryOperator;
import java.util.stream.LongStream;
public class FibUtil {
public static LongStream fibStream() {
return LongStream.iterate( 1l, new LongUnaryOperator() {
private long lastFib = 0;
@Override public long applyAsLong( long operand ) {
long ret = operand + lastFib;
lastFib = operand;
return ret;
}
});
}
public static long fib(long n) {
return fibStream().limit( n ).reduce((prev, last) -> last).getAsLong();
}
}

View file

@ -1,17 +1,17 @@
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);
};
});
(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);
})();

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 Y(dn) {
return (function(fn) {
return fn(fn);
}(function(fn) {
return dn(function() {
return fn(fn).apply(null, arguments);
});
}));
}
var fib = fibonacciGenerator();
var fib = Y(function(fn) {
return function(n) {
if (n === 0 || n === 1) {
return n;
}
return fn(n - 1) + fn(n - 2);
};
});

View file

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

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

@ -23,10 +23,11 @@ enum class Fibonacci {
abstract operator fun invoke(n: Long): Long
}
fun main(args: Array<String>) {
fun main(a: Array<String>) {
val r = 0..30L
Fibonacci.values() forEach {
print("\n${it.name()}: ")
r forEach { i -> print(" " + it(i)) }
Fibonacci.values().forEach {
print("${it.name}: ")
r.forEach { i -> print(" " + it(i)) }
println()
}
}

View file

@ -0,0 +1,34 @@
print "Rosetta Code - Fibonacci sequence": print
print " n Fn"
for x=-12 to 12 '68 max
print using("### ", x); using("##############", FibonacciTerm(x))
next x
print
[start]
input "Enter a term#: "; n$
n$=lower$(trim$(n$))
if n$="" then print "Program complete.": end
print FibonacciTerm(val(n$))
goto [start]
function FibonacciTerm(n)
n=int(n)
FTa=0: FTb=1: FTc=-1
select case
case n=0 : FibonacciTerm=0 : exit function
case n=1 : FibonacciTerm=1 : exit function
case n=-1 : FibonacciTerm=-1 : exit function
case n>1
for x=2 to n
FibonacciTerm=FTa+FTb
FTa=FTb: FTb=FibonacciTerm
next x
exit function
case n<-1
for x=-2 to n step -1
FibonacciTerm=FTa+FTc
FTa=FTc: FTc=FibonacciTerm
next x
exit function
end select
end function

View file

@ -14,7 +14,24 @@ 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,0) end
function trfib(i) return a(i-1,1,0) end
--table-recursive
fib_n = setmetatable({1, 1}, {__index = function(z,n) return z[n-1] + z[n-2] end})
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,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
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
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,5 @@
> f := n -> ifelse(n<3,1,f(n-1)+f(n-2));
> f(2);
1
> f(3);
2

View file

@ -0,0 +1,60 @@
MODULE Fibonacci;
IMPORT
Out := NPCT:Console;
PROCEDURE Fibs(VAR r: ARRAY OF LONGREAL);
VAR
i: LONGINT;
BEGIN
r[0] := 1.0; r[1] := 1.0;
FOR i := 2 TO LEN(r) - 1 DO
r[i] := r[i - 2] + r[i - 1];
END
END Fibs;
PROCEDURE FibsR(n: LONGREAL): LONGREAL;
BEGIN
IF n < 2. THEN
RETURN n
ELSE
RETURN FibsR(n - 1) + FibsR(n - 2)
END
END FibsR;
PROCEDURE Show(r: ARRAY OF LONGREAL);
VAR
i: LONGINT;
BEGIN
Out.String("First ");Out.Int(LEN(r),0);Out.String(" Fibonacci numbers");Out.Ln;
FOR i := 0 TO LEN(r) - 1 DO
Out.LongRealFix(r[i],8,0)
END;
Out.Ln
END Show;
PROCEDURE Gen(s: LONGINT);
VAR
x: POINTER TO ARRAY OF LONGREAL;
BEGIN
NEW(x,s);
Fibs(x^);
Show(x^)
END Gen;
PROCEDURE GenR(s: LONGINT);
VAR
i: LONGINT;
BEGIN
Out.String("First ");Out.Int(s,0);Out.String(" Fibonacci numbers (Recursive)");Out.Ln;
FOR i := 1 TO s DO
Out.LongRealFix(FibsR(i),8,0)
END;
Out.Ln
END GenR;
BEGIN
Gen(10);
Gen(20);
GenR(10);
GenR(20);
END Fibonacci.

View file

@ -1,11 +1 @@
fib(n)={
if(n<0,return((-1)^(n+1)*fib(n)));
my(a=0,b=1,t);
while(n,
t=a+b;
a=b;
b=t;
n--
);
a
};
apply(n->if(n<2,n,my(s=self());s(n-2)+s(n-1)), [1..10])

View file

@ -1 +1,13 @@
fib(n)=my(k=0);while(n--,k++;while(!issquare(5*k^2+4)&&!issquare(5*k^2-4),k++));k
F=[];
fib(n)={
if(n>#F,
F=concat(F, vector(n-#F));
F[n]=fib(n-1)+fib(n-2)
,
if(n<2,
n
,
if(F[n],F[n],F[n]=fib(n-1)+fib(n-2))
)
);
}

View file

@ -0,0 +1,11 @@
fib(n)={
if(n<0,return((-1)^(n+1)*fib(n)));
my(a=0,b=1,t);
while(n,
t=a+b;
a=b;
b=t;
n--
);
a
};

View file

@ -0,0 +1,7 @@
matantihadamard(n)={
matrix(n,n,i,j,
my(t=j-i+1);
if(t<1,t%2,t<3)
);
}
fib(n)=matdet(matantihadamard(n))

View file

@ -0,0 +1,7 @@
fib(n)=
{
my(g=2^(n+1)-1);
sum(i=2^(n-1),2^n-1,
bitor(i,i<<1)==g
);
}

View file

@ -0,0 +1 @@
fib(n)=my(k=0);while(n--,k++;while(!issquare(5*k^2+4)&&!issquare(5*k^2-4),k++));k

View file

@ -1 +1 @@
([1,1;1,0]^n)[1,2]
fibo(n)=([1,1;1,0]^n)[1,2]

View file

@ -1,10 +1,6 @@
fib(n)={
if(n<2,
if(n<0,
(-1)^(n+1)*fib(n)
,
n
)
n
,
fib(n-1)+fib(n)
)

View file

@ -0,0 +1,4 @@
function FiboMax(n: integer):Extended; //maXbox
begin
result:= (pow((1+SQRT5)/2,n)-pow((1-SQRT5)/2,n))/SQRT5
end;

View file

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

View file

@ -1 +1 @@
my constant @fib = 0, 1, *+* ... *;
constant @fib = 0, 1, *+* ... *;

View file

@ -1,2 +1,2 @@
my constant @neg_fib = 0, 1, *-* ... *;
sub fib ($n) { $n >= 0 and @fib[$n] or @neg_fib[-$n]; }
constant @neg-fib = 0, 1, *-* ... *;
sub fib ($n) { $n >= 0 ?? @fib[$n] !! @neg-fib[-$n] }

View file

@ -1,3 +1,4 @@
use experimental :cached;
proto fib (Int $n --> Int) is cached {*}
multi fib (0) { 0 }
multi fib (1) { 1 }

View file

@ -1,26 +1,9 @@
function fib ($n) {
if ($n -eq 0) { return 0 }
if ($n -eq 1) { return 1 }
$m = 1
if ($n -lt 0) {
if ($n % 2 -eq -1) {
$m = 1
} else {
$m = -1
}
$n = -$n
function FibonacciNumber ( $count )
{
$answer = @(0,1)
while ($answer.Length -le $count)
{
$answer += $answer[-1] + $answer[-2]
}
$a = 0
$b = 1
for ($i = 1; $i -lt $n; $i++) {
$c = $a + $b
$a = $b
$b = $c
}
return $m * $b
return $answer
}

View file

@ -1,8 +1,4 @@
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)) }
}
}
$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

@ -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,5 +1,7 @@
def fibFastRec(n):
def fib(prvprv, prv, c):
if c < 1: return prvprv
else: return fib(prv, prvprv + prv, c - 1)
if c < 1:
return prvprv
else:
return fib(prv, prvprv + prv, c - 1)
return fib(0, 1, n)

View file

@ -1,4 +1,5 @@
def fibGen(n,a=0,b=1):
def fibGen(n):
a, b = 0, 1
while n>0:
yield a
a,b,n = b,a+b,n-1
a, b, n = b, a+b, n-1

View file

@ -1,23 +1,23 @@
/*REXX program calculates the Nth Fibonacci number, N can be zero or neg*/
numeric digits 210000 /*be able to handle some big 'uns*/
parse arg x y . /*allow a single number or range.*/
if x=='' then do; x=-40; y=+40; end /*No input? Use range -40 ──► +40*/
if y=='' then y=x /*if only one number, show fib(n)*/
w=max(length(x), length(y)) /*used for making output pretty. */
fw=10 /*minmum maximum width. Ka-razy.*/
do j=x to y; q=fib(j) /*process each Fibonacci request.*/
L=length(q) /*obtain the length (width) of Q.*/
fw=max(fw, L) /*fib# 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 seq. of x──►y */
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────FIB subroutine──────────────────────*/
fib: procedure; parse arg n; a=0; b=1; na=abs(n) /*use |n| */
if na<2 then return na /*handle 3 special cases (-1,0,1)*/
/* [↓] method is non-recursive.*/
do k=2 to na; s=a+b; a=b; b=s /*sum the numbers up to │n│ */
end /*k*/ /* [↑] (only positive Fibs used)*/
/* [↓] na//2 [same as] na/2==1 */
if n>0 | na//2 then return s /*if positive or odd negative ···*/
return -s /*return a negative Fib number. */
/*REXX program calculates the Nth Fibonacci number, N can be zero or negative. */
numeric digits 210000 /*be able to handle ginormous numbers. */
parse arg x y . /*allow a single number or a range. */
if x=='' | x=="," then do; x=-40; y=+40; end /*No input? Then use range -40 ──► +40*/
if y=='' | y=="," then y=x /*if only one number, display fib(X).*/
w=max(length(x), length(y) ) /*W: used for making formatted output.*/
fw=10 /*Minimum maximum width. Sounds ka─razy*/
do j=x to y; q=fib(j) /*process all of the Fibonacci requests*/
L=length(q) /*obtain the length (decimal digs) of Q*/
fw=max(fw, L) /*fib number length, or the max so far.*/
say 'Fibonacci('right(j,w)") = " right(q,fw) /*right justify Q*/
if L>10 then say 'Fibonacci('right(j, w)") has a length of" L
end /*j*/ /* [↑] list a Fib. sequence of x──►y */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fib: procedure; parse arg n; an=abs(n) /*use │n│ (the absolute value of N).*/
a=0; b=1; if an<2 then return an /*handle two special cases: zero & one.*/
/* [↓] this method is non─recursive. */
do k=2 to an; $=a+b; a=b; b=$ /*sum the numbers up to │n│ */
end /*k*/ /* [↑] (only positive Fibs nums used).*/
/* [↓] an//2 [same as] (an//2==1).*/
if n>0 | an//2 then return $ /*Positive or even? Then return sum. */
return -$ /*Negative and odd? Return negative sum*/

View file

@ -1,30 +1,12 @@
#![feature(zero_one)]
use std::num::One;
use std::ops::Add;
struct Fib<T> {
curr: T,
next: T,
}
impl<T> Fib<T> where T: One {
fn new() -> Self {
Fib {curr: T::one(), next: T::one()}
}
}
impl<T> Iterator for Fib<T> where T: Add<T, Output=T> + Copy {
type Item = T;
fn next(&mut self) -> Option<Self::Item>{
let new = self.curr + self.next;
self.curr = self.next;
self.next = new;
Some(self.curr)
}
}
use std::mem;
fn main() {
for i in Fib::<u64>::new() {
println!("{}", i);
let mut prev = 0;
// Rust needs this type hint for the checked_add method
let mut curr = 1usize;
while let Some(n) = curr.checked_add(prev) {
prev = curr;
curr = n;
println!("{}", n);
}
}

View file

@ -1,16 +1,12 @@
use std::mem;
fn main() {
fn fib(n: i32) -> i32 {
fn _fib(n: i32, a: i32, b: i32) -> i32 {
match (n, a, b) {
(0, _, _) => a,
_ => _fib(n-1, a+b, a)
}
}
fibonacci(0,1);
}
_fib(n, 0, 1)
}
for n in 0..20 {
println!("{}", fib(n));
fn fibonacci(mut prev: usize, mut curr: usize) {
mem::swap(&mut prev, &mut curr);
if let Some(n) = curr.checked_add(prev) {
println!("{}", n);
fibonacci(prev, n);
}
}

View file

@ -0,0 +1,14 @@
#![feature(conservative_impl_trait)]
fn main() {
for num in fibonacci_gen(10) {
println!("{}", num);
}
}
fn fibonacci_gen(terms: i32) -> impl Iterator<Item=f64> {
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).floor())
}

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,11 @@
data fib;
a=0;
b=1;
do n=0 to 20;
f=a;
output;
a=b;
b=f+a;
end;
keep n f;
run;

View file

@ -0,0 +1,14 @@
options cmplib=work.f;
proc fcmp outlib=work.f.p;
function fib(n);
if n = 0 or n = 1
then return(1);
else return(fib(n - 2) + fib(n - 1));
endsub;
run;
data _null_;
x = fib(5);
put 'fib(5) = ' x;
run;

View file

@ -1,12 +0,0 @@
/* building a table with fibonacci sequence */
data fib;
a=0;
b=1;
do n=0 to 20;
f=a;
output;
a=b;
b=f+a;
end;
keep n f;
run;

View file

@ -0,0 +1,4 @@
select round ( exp ( sum (ln ( ( 1 + sqrt( 5 ) ) / 2)
) over ( order by level ) ) / sqrt( 5 ) ) fibo
from dual
connect by level <= 10;

View file

@ -0,0 +1,3 @@
select round ( power( ( 1 + sqrt( 5 ) ) / 2, level ) / sqrt( 5 ) ) fib
from dual
connect by level <= 10;

View file

@ -0,0 +1,14 @@
INTEGER PROCEDURE fibonacci(n);
INTEGER n;
BEGIN
INTEGER lo, hi, temp, i;
lo := 0;
hi := 1;
FOR i := 1 STEP 1 UNTIL n - 1 DO
BEGIN
temp := hi;
hi := hi + lo;
lo := temp
END;
fibonacci := hi
END;

View file

@ -0,0 +1,2 @@
f = { |n| if(n < 2) { n } { f.(n-1) + f.(n-2) } };
(0..20).collect(f)

View file

@ -0,0 +1,2 @@
f = { |n| var u = neg(sign(n)); if(abs(n) < 2) { n } { f.(2 * u + n) + f.(u + n) } };
(-20..20).collect(f)

View file

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

View file

@ -0,0 +1,2 @@
f = { |n| var a = [1, 1]; n.do { a = a.addFirst(a[0] + a[1]) }; a.reverse };
f.(18)

View file

@ -0,0 +1,9 @@
10 REM Only positive numbers
20 LET n=10
30 LET n1=0: LET n2=1
40 FOR k=1 TO n
50 LET sum=n1+n2
60 LET n1=n2
70 LET n2=sum
80 NEXT k
90 PRINT n1