Calculate the Nth term

Sort by

recency

|

825 Discussions

|

  • + 0 comments

    This is my approach to solve this challenge!

    int find_nth_term(int n, int a, int b, int c) {
        int ans = 0, ansa, ansb, ansc;
        if(n == 1) ans = a;
        if(n == 2) ans = b;
        if(n == 3) ans = c;
        if(n == 4) ans = c + b + a;
        if(n > 4) {
            ansc = find_nth_term(n - 3, a , b , c);
            ansb = find_nth_term(n - 2, a , b , c);
            ansa = find_nth_term(n - 1, a , b , c);
            ans += ansa + ansb + ansc;
        }
        return ans;
    }
    
  • + 0 comments

    Understanding recursion in this series example highlights how each step builds on the previous ones, a concept that’s surprisingly similar to structuring a strategy for private equity lead generation.

  • + 0 comments

    My take

    int find_nth_term(int n, int a, int b, int c) {
        if (n == 1)
        {
            return a;
        }
        return find_nth_term(--n, b, c, (a+b+c));
    }
    
  • + 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;
    }
    
  • + 0 comments

    Here is Calculate the Nth term solution in c - https://programmingoneonone.com/hackerrank-calculate-the-nth-term-solution-in-c.html