Algorithms_in_C++  1.0.0
Set of algorithms implemented in C++.
fibonacci_fast.cpp File Reference

Faster computation of Fibonacci series. More...

#include <cinttypes>
#include <cstdio>
#include <iostream>
Include dependency graph for fibonacci_fast.cpp:

Functions

uint64_t fib (uint64_t n)
 
int main ()
 

Variables

const uint64_t MAX = 93
 
uint64_t f [MAX] = {0}
 

Detailed Description

Faster computation of Fibonacci series.

An efficient way to calculate nth fibonacci number faster and simpler than \(O(n\log n)\) method of matrix exponentiation This works by using both recursion and dynamic programming. as 93rd fibonacci exceeds 19 digits, which cannot be stored in a single long long variable, we can only use it till 92nd fibonacci we can use it for 10000th fibonacci etc, if we implement bigintegers. This algorithm works with the fact that nth fibonacci can easily found if we have already found n/2th or (n+1)/2th fibonacci It is a property of fibonacci similar to matrix exponentiation.

Author
Krishna Vedala
See also
fibonacci_large.cpp, fibonacci.cpp, string_fibonacci.cpp

Function Documentation

◆ fib()

uint64_t fib ( uint64_t  n)

Algorithm

30  {
31  if (n == 0)
32  return 0;
33  if (n == 1 || n == 2)
34  return (f[n] = 1);
35 
36  if (f[n])
37  return f[n];
38 
39  uint64_t k = (n % 2 != 0) ? (n + 1) / 2 : n / 2;
40 
41  f[n] = (n % 2 != 0) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1))
42  : (2 * fib(k - 1) + fib(k)) * fib(k);
43  return f[n];
44 }

◆ main()

int main ( )

Main function

47  {
48  // Main Function
49  for (uint64_t i = 1; i < 93; i++) {
50  std::cout << i << " th fibonacci number is " << fib(i) << std::endl;
51  }
52  return 0;
53 }
Here is the call graph for this function:

Variable Documentation

◆ f

uint64_t f[MAX] = {0}

Array of computed fibonacci numbers

◆ MAX

const uint64_t MAX = 93

maximum number that can be computed - The result after 93 cannot be stored in a uint64_t data type.

f
uint64_t f[MAX]
Definition: fibonacci_fast.cpp:27
std::cout
k
ll k
Definition: matrix_exponentiation.cpp:48
fib
uint64_t fib(uint64_t n)
Definition: fibonacci_fast.cpp:30
std::endl
T endl(T... args)