AlgoPlus v0.1.0
Loading...
Searching...
No Matches
fib.h
1#ifndef FIB_H
2#define FIB_H
3
4#ifdef __cplusplus
5#include <cstdint>
6#include <iostream>
7#include <math.h>
8#include <vector>
9#endif
10
17int64_t fibonacci(int64_t n) {
18 if (n <= 1) {
19 return n;
20 }
21 return fibonacci(n - 1) + fibonacci(n - 2);
22}
23
30int64_t fibonacci_dp(int64_t n) {
31 std::vector<int64_t> dp(n + 2);
32 dp[0] = 0;
33 dp[1] = 1;
34 for (int64_t i = 2; i <= n; i++) {
35 dp[i] = dp[i - 1] + dp[i - 2];
36 }
37 return dp[n];
38}
39
46int64_t fibonacci_bottom_up(int64_t n) {
47 int64_t a = 0, b = 1, c = 0;
48 if (n == 0) {
49 return 0;
50 }
51 for (int64_t i = 2; i <= n; i++) {
52 c = a + b;
53 a = b;
54 b = c;
55 }
56 return b;
57}
58
65int64_t fibonacci_binet(int64_t n) {
66 double phi = (std::sqrt(5) + 1) / 2;
67 return (int64_t)std::round(std::pow(phi, n) / sqrt(5));
68}
69#endif