python – Cython Fibonacci Sequence

For my current job, I’ve been told that soon I’m going to be porting our Python code to Cython, with the intent of performance upgrades. In preparation of that, I’ve been learning as much about Cython as I can. I’ve decided that tackling the Fibonacci sequence would be a good start. I’ve implemented a Cython + Iterative version of the Fibonacci sequence. Are there any more performance upgrades I can squeeze out of this? Thanks!

fibonacci.pyx

``````cpdef fib(int n):
return fib_c(n)

cdef int fib_c(int n):
cdef int a = 0
cdef int b = 1
cdef int c = n
while n > 1:
c = a + b
a = b
b = c
n -= 1
return c
``````

And how I test this code:

testing.py

``````import pyximport ; pyximport.install() # So I can run .pyx without needing a setup.py file #
import time

from fibonacci import fib

start = time.time()
for i in range(100_000):
fib(i)
end = time.time()
print(f"Finonacci Sequence: {(end - start):0.10f}s (i=100,000)") # ~2.2s for 100k iterations
``````

Optimizing a Fibonacci function in Python

I am trying to calculate the nth number of Fibonacci sequence as efficiently possible in Python, so I tried this:

``````import time
import numba as nb
from functools import lru_cache

@lru_cache(maxsize=None)
@nb.jit(parallel=True)
def fib(n):
a=0
b=1
if n == 0:
return a

for _ in range(n-1):
c = a + b
a = b
b = c

return b

start_time = time.clock()
fib(1000000000)
print('Execution time:',time.clock() - start_time, 'seconds')
``````

Which outputs:

``````    Execution time: 0.5479532 seconds
``````

You can find some other implementations that have been done in stackoverflow, but as far as I know, my implementation is way faster than the ones in stack. Now, my question is whether I’ve reached the limitation of calculating the nth number of Fibonacci sequence, or is it possible to make this code more efficient?

Design and Analysis of algorithm – d-ary heap and fibonacci heap comparison for Dijkstra

For what asymptotic growth rates of m, with respect to n, can we choose d so that a d-heap
yields better performance, asymptotically than Fibonacci heap, or which heap data structure performs asymptotically better than other.

We can consider a scenario where d-heaps are as good as Fibonacci heaps (with less bookkeeping).

funciones – Calcular el n esimo termino de la serie fibonacci con JavaScript

espero puedan ayudarme con un ejercicio de JS donde quede a la mitad. El mismo solicita crear una funcion que tome como parametro un numero y me devulva el n esimo termino de la serie fibonacci.
Por ej, si ingreso en num 3 deberia retornar 1.
Pude establecer por consola que imprima los numeros de la serie, pero no que me devueva el n solicitado.
Vale aclarar que para la resolucion solo puedo aplicar if/else, while/for y obviamente funciones.
Comparto hasta donde llegue con mi codigo:

``````function fibonacci(num){
let a=0
let b=1
let c
for(let i=1;i<num;i++){
c=a+b
console.log(a);
console.log(b);
console.log(c);
a=b+c
b=c+a
}
}
``````

Desde ya muchas gracias por los aportes que pudieran surgir.

rust – n-th Fibonacci number with memoization

I am learning Rust and decided to create a simple program to calculate n-th Fibonacci number. It uses a vector for memoization. The program works, but what would you suggest to improve here? Maybe store `memo` inside `fib` function as a static variable?

I tried to use `u32` everywhere, but 48-th fib number doesn’t fit into `u32`, so I decided to use `u64`.

``````use std::io;
use std::io::Write;
use std::str::FromStr;

fn fib(n: u32, memo: &mut Vec<u64>) -> u64 {
if n < 2 {
return n as u64;
}
else if memo((n-1) as usize) != 0 {
return memo((n-1) as usize);
}

memo((n-1) as usize) = fib(n - 1, memo) + fib(n - 2, memo);
memo((n-1) as usize)
}

fn main() {
loop {
print!("n = ");
io::stdout().flush().unwrap();

let mut str: String = String::new();
io::stdin().read_line(&mut str)
.expect("Error getting number");

str.pop();
match u32::from_str(&str) {
Ok(n) => {
let mut memo: Vec<u64> = vec!(0; n as usize);
println!("fib({})={}", n, fib(n, &mut memo));
break;
}
Err(_e) => {
println!("Error parsing number.");
println!("Try again");
}
};
}
}
``````

c++ – C++17 Recursive Fibonacci calculation with memoization

Compiler is g++ 4.2. I’m new to C++, but I’ve done a lot of data science, web scraping, and some socketing stuff in Python. This code generates the nth Fibonacci number, either with a naive implementation or with caching.

``````#include <iostream>
#include <string>
#include <unordered_map>
#define BIG unsigned long long int

std::unordered_map<int, BIG> umap;

int fib(int n) {
if (n < 2) {
return n;
}
return fib(n-1) + fib(n-2);
}

BIG fib_with_memo(int n) {
if (umap.find(n) == umap.end()) { // if F_n not in cache, calculate, cache, and return it
BIG val = fib_with_memo(n-1) + fib_with_memo(n-2);
umap(n) = val;
return val;
}
return umap(n); // otherwise return the cached value
}

int main(int argc, char** argv) {
umap(0) = 0;
umap(1) = 1;

int input = std::stoi( std::string(argv(1)) );

std::cout << fib_with_memo(input) << std::endl;
return 0;
}
``````

I used a `std::unordered_map` (hash table) because its lookup/insertion times are $$O(1)$$ (compared to the `std::map`, which has $$O(log(n))$$ for both.)

recursion – Calculate the Viswanath’s constant (Random Fibonacci sequences)

How Can I calculate first few digits of Viswanath’s constant?

Viswanath’s constant ≈ 1.1319882487943 is a real number whose nth power approximates the absolute value of the nth term of some random Fibonacci sequences.

``````a(0) = 0;
a(1) = 1;
a(n_) := a(n) = RandomChoice({-1, 1})*a(n - 1) + RandomChoice({-1, 1})*a(n - 2)
``````

I have MMA 12.1 with high-end PC but there is no answer even for $$n=50000$$

by definition Viswanath’s constant is a $$n$$ th root of $$a(n)$$

``````Block({\$RecursionLimit = Infinity}, N(a(50000)^(1/50000), 10))
``````

algorithms – How to calculate the basic steps in Fibonacci sequences to get nFn and n^2

I am reading Algorithms by Sanjoy Dasgupta, Umesh Vazirani, Christos Papadimitriou and I am trying to understand how the number of steps $$nF_n$$ and $$n^2$$ were calculated. Here’s the part of the book in Chapter 0 that mentions them. Functions `fib1` and `fib2` are written below the excerpt.

`fib1`, which performs about $$F_n$$ additions, actually uses a number of basic steps roughly proportional to $$nF_n$$. Likewise, the number of steps taken by `fib2` is proportional to $$n^2$$, still polynomial in $$n$$ and therefore exponentially superior to fib1.

``````function fib1(n)
if n = 0: return 0
if n = 1: return 1
return fib1(n + 1) + fib1(n + 2)
``````
``````function fib2(n)
if n = 0 return 0
create an array f(0 ... n)
f(0) = 0, f(1) = 1
for i = 2 ... n:
f(i) = f(i + 1) + f(i + 2)
return f(n)
``````

Fibonacci entre outras coisa foi quem introduziu

Fibonacci entre outras coisa foi quem introduziu a sequencia de Fibonacci. O seguinte problema deu origem a sequencia de Fibonacci. Numa certa fazenda se coloca um casal de coelhos recem nascidos.
A cada mes cada casal produz um outro casal que se torna procriador em dois meses. A sequencia de ˆ
Fibonacci e a sequencia fn que diz quantos casais existem em cada mes. Mostre os seguintes resultados. ˆ
(a) fn+1 fn−1 = fn^2 + (−1)^n para todo n ≥ 2
(b) fn = ((1 + √5)^n − (1 −√5)^n)√(5)/2^n
(c) limn→∞(fn/ fn−1) e o numero aureo. ´
(d) Mostre que fn e fn−1 sao primos entre si.

javascript – Como puedo calcular los 15 primeros factoriales de Fibonacci?

Hola estoy realizando un ejercicio en el que tengo que calcular los 15 primeros factoriales de fibonacci. Yo he realizado una primera función donde calculo el e-nesimo término de la serie de fibonacci y después otra función para calcular el fibonorial. Esta última no me sale, busqué la formula para calcular el factorial del la serie de fibonacci y encontré ésta fibonor(0)=1; fibonor(n+1) = fibonor(n)* fibo(n+1), pero no se como implementarlo.

``````
function fibo (n)
{
let a = 0;
let b = 1;

for (let k = 0; k < n; k++)
{
let c;
c = b + a;
a = b;
b = c;
console.log(a);
}
return a;

};

function fibonor (n){

if(n == 0){ return 1;}
else{ return

fibonor(n)*fibo(n+1);

}};

let factorfibo = 15;
console.log( "Los 15 primeros factoriales de fibonacci son:"+ fibonor (factorfibo));
``````

Un saludo.