Skip to content

Instantly share code, notes, and snippets.

@SergeyNarozhny
Last active April 13, 2017 22:11
Show Gist options
  • Save SergeyNarozhny/e31afe9f42ef9f81584d2746d26cb98f to your computer and use it in GitHub Desktop.
Save SergeyNarozhny/e31afe9f42ef9f81584d2746d26cb98f to your computer and use it in GitHub Desktop.
#include <cassert>
#include <iostream>
#include <unordered_map>
class Fibonacci final {
public:
static int get(int n) {
assert(n >= 0);
if (n == 0 || n == 1) {
return n;
}
static std::unordered_map<int, int> cache;
auto &result = cache[n];
if (result == 0) {
result = get(n-2) + get(n-1);
}
return result;
}
}
int main() {
int n;
std::cin >> n;
stf::cout << Fibonacci.get(n) << std::endl;
return 0;
}
@SergeyNarozhny
Copy link
Author

Or using loop:
assert(n >= 0); static std::unordered_map<int, int> cache; cache[0] = 0; cache[1] = 1; for (int i = 2; i <= n; i++) { cache[i] = cache[i - 2] + cache[i - 1]; } return cache[n];

@SergeyNarozhny
Copy link
Author

Or using vector:
static std::vector<int> cache; cache.resize(n+1); ...

@SergeyNarozhny
Copy link
Author

Or using only two prev calculated numbers:
int prev = 0; int cur = 1; for (int i = 2; i <= n; i++) { int new_cur = prev + cur; prev = cur; cur = new_cur; } return cur;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment