TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
fibonacci_fast.cpp
Go to the documentation of this file.
1
18#include <cinttypes>
19#include <cstdio>
20#include <iostream>
21
27#define MAX 93
28
30uint64_t fib(uint64_t n) {
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) {
38 std::cerr
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}
49
51int main() {
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}
uint64_t fib(uint64_t n)
int main()