Calculate the Nth term

  • + 0 comments

    While the recursive solution is relatively trivial, the optimal solution is actually not recursive at all, and instead uses a cache in order to stop having to recalculate the same position every time you need it.

    int find_nth_term(int n, int a, int b, int c) {
        //Write your code here.
        int *cache = malloc(sizeof(int) * (n + 1));
        cache[1] = a;
        cache[2] = b;
        cache[3] = c;
        
        if (n <= 3) return cache[n];
        
        for (int i = 4; i <= n; i++) {
            cache[i] = cache[i - 1] + cache[i - 2] + cache[i - 3];
        }
        
      
        int ret = cache[n];
        free(cache);
        return ret;
    }