Javascript - Better Alternate to Recursive call

Viewed 209

I have this following problem. I need to calculate a number x based on time t, x would be represented as M(t). We have the following

  • M(0) = 1
  • M(1) = 1
  • M(2) = 2
  • M(2t) = M(t) + M(t + 1) + t (for t > 1)
  • M(2t + 1) = M(t - 1) + M(t) + 1 (for t >= 1)

With that being said the first thing i had in mind to implement this is by using recursion

function CalculateForTime(t) {
    if (t == 0 || t == 1) {
        return 1;
    }
    else if (t == 2) {
        return 2;
    }
    else if (t % 2 == 0) {
        t = t / 2;
        return CalculateForTime(t) + CalculateForTime(t + 1) + t;
    }
    else {
        t = (t - 1) / 2;
        return CalculateForTime(t - 1) + CalculateForTime(t) + 1;
    }
}

This works however it breaks when running on a large number t for example 1^20

I tried looking into tail call recursion or substituting the recursion approach to an iteration approach but couldn't really figure it out.

If tail recursion or iteration is the way to go then please I need help on converting this. If not then I'm open to different methods on making this more optimized.

Thank you, Omar.

3 Answers
Related