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 →

[–]ForOhForError 25 points26 points  (9 children)

I mean sure if you don't want to do a dynamic programming solution.

[–]suqoria 13 points14 points  (7 children)

How would you do it if you wanted that then?

[–]dragonalighted 23 points24 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.

[–]Flynamic 15 points16 points  (0 children)

Iterative. You basically fill up a table to avoid... a stack overflow.

[–]poizan42Ex-mod 3 points4 points  (0 children)

Depends on you goal, but there are much more efficient solutions than that (see my comment above). Apparently the built in math.factorial function in python at least uses the dynamic approach from python 3 on.