fork(8) download
  1. //
  2. // main.cpp
  3. // Memoizator
  4. //
  5. //
  6. #include <iostream>
  7. #include <map>
  8. #include <tuple>
  9. #define MEMOIZATOR(N, R, ...) \
  10. R _ ## N (__VA_ARGS__); \
  11. std::map<std::tuple<__VA_ARGS__>, R> _memo_ ## N; \
  12. template <typename ... Args> \
  13. R N (Args ... args) { \
  14.   auto& _memo = _memo_ ## N; \
  15.   auto result = _memo.find(std::make_tuple(args...)); \
  16.   if (result != _memo.end()) { \
  17.   return result->second; \
  18.   } \
  19.   else { \
  20.   auto result = _ ## N (args...); \
  21.   _memo[std::make_tuple(args...)] = result; \
  22.   return result; \
  23.   } \
  24. }
  25. MEMOIZATOR(fibonacci, long int, int);
  26.  
  27. int function_count = 0;
  28.  
  29. long int _fibonacci(int n) {
  30. function_count++;
  31. if (n == 1 or n == 2) {
  32. return 1;
  33. }
  34. return fibonacci(n - 1) + fibonacci(n - 2);
  35. }
  36.  
  37. using namespace std;
  38. int main(int argc, const char * argv[]) {
  39. // insert code here...
  40. cout << "Result: " << fibonacci(40) << endl;
  41. cout << "Fibonacci executed " << function_count << " times." <<endl;
  42. return 0;
  43. }
  44.  
  45.  
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
Result: 102334155
Fibonacci executed 40 times.