Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
Loading...
Searching...
No Matches
fibonacci_fast.cpp File Reference

Faster computation of Fibonacci series. More...

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

Macros

#define MAX   93
 

Functions

uint64_t fib (uint64_t n)
 
int main ()
 

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

Macro Definition Documentation

◆ MAX

#define MAX   93

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

Function Documentation

◆ fib()

uint64_t fib ( uint64_t n)

Algorithm

30 {
31 static uint64_t f1 = 1,
32 f2 = 1; // using static keyword will retain the values of
33 // f1 and f2 for the next function call.
34
35 if (n <= 2)
36 return f2;
37 if (n >= 93) {
39 << "Cannot compute for n>93 due to limit of 64-bit integers\n";
40 return 0;
41 }
42
43 uint64_t temp = f2; // we do not need temp to be static
44 f2 += f1;
45 f1 = temp;
46
47 return f2;
48}

◆ main()

int main ( void )

Main function

51 {
52 // Main Function
53 for (uint64_t i = 1; i < 93; i++) {
54 std::cout << i << " th fibonacci number is " << fib(i) << std::endl;
55 }
56 return 0;
57}
T endl(T... args)
uint64_t fib(uint64_t n)
Definition fibonacci_fast.cpp:30
Here is the call graph for this function: