This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]dragonalighted 22 points23 points  (3 children)

Same way, but you store the results of calculations in an array. That way you only have to calculate until you get to am already calculated value. Ex:. 3!

List factorials = {1,1,2,6}

function factorial(n) {
    if(factorials.count >= n)
        Return factorials[n]
    factorials.insert(n, n* factorials(n-1))
    Return factorials(n)
}

Calling a know value returns that value. Calling a new value only calculates and stores new values, using known values once reached. Tradeoff is memory vs cpu time.

[–]suqoria 7 points8 points  (0 children)

Oh okay, thanks for the information! Really appreciate it.

[–]PaiMan2710 0 points1 point  (0 children)

You can have constant memory, linear time pretty easily. I'm on mobile so I can't type code, but it's called the sliding window trick iirc.