Search code examples
c++algorithmmathfactorial

Memoized, recursive factorial function?


I know how to do memoization in Python easily but I need a faster way to compute them, so I am using C++. However, I have no clue how to memoize. I understand that it's about storing values into an array or vector and then scanning for its value when retrieving, but it'd be really helpful to see how this is done so I can try its speed.


Solution

  • Well the neatest way I can think of to do this in C++ is probably using a function object to store the memoized values. I guess this is probably slightly similar to your python decorator, although I have never really done any python. The code would look something like this:

    template <typename T, T (*calc)(T)>
    class mem {
      std::map<T,T> mem_map;
    
    public:
      T operator()(T input) {
        typename std::map<T,T>::iterator it;
    
        it = mem_map.find(input);
        if (it != mem_map.end()) {
          return it->second;
        } else {
          T output = calc(input);
          mem_map[input] = output;
          return output;
        }
      }
    };
    

    The code defines a template class that takes in a typename and a function pointer, the function operator is then defined on the class allowing it to be called. The function operator takes in an input value checks if said value is in a map, then either simply returns it from the map or calculates it (using the function pointer), adds it to the map and then returns it.

    So assuming you define some processing function like say:

    int unity(int in) { return in; }
    

    You would use the code like this:

    mem<int, unity> mem_unity;
    int y;
    y = mem_unity(10);
    

    So we define an instance of the mem class which takes our value type and processing function as template parameters, then simply call this class as a function.