-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcached_fib.cpp
42 lines (37 loc) · 861 Bytes
/
cached_fib.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <Rcpp.h>
#include <algorithm>
#include <vector>
#include <stdexcept>
#include <cmath>
#include <iostream>
using namespace Rcpp;
class Fib {
public:
Fib(unsigned int n = 1000) {
cache.resize(n);
std::fill(cache.begin(), cache.end(), NAN);
cache[0] = 0.0;
cache[1] = 1.0;
}
double cached_fibCpp(int x) {
if (x < 0) {
return (double) NAN;
}
if (x >= (int) cache.size()) {
throw std::range_error("x too large for implementation");
}
if (x < 2) {
return x;
}
if (! ::isnan(cache[x])) return cache[x];
cache[x] = cached_fibCpp(x - 1) + cached_fibCpp(x - 2);
return cache[x];
}
private:
std::vector<double> cache;
};
Fib f = Fib(2000);
// [[Rcpp::export]]
double cached_fibCpp(const int a) {
return f.cached_fibCpp(a);
}