user2170674
user2170674

Reputation: 41

Ocaml stack overflow with easy computations

Here is my code:

let rec sum n =  
    if n <= 0 then 0
    else if n / 2 * 2 = n then 3 * n + 50 * (sum n-2)
    else n + 10 * (sum n-1);;

The math problem is simply as following:

sn =
    0 if n = 0
    50*sn-2 + 3*n, if n > 0 and n is even
    10*sn-1 + n  , if n > 0 and n is odd

When I test sum 5, it popped out "stack overflow" error as following:

Stack overflow during evaluation (looping recursion?).

Could anyone help me out?

Upvotes: 3

Views: 287

Answers (2)

jerry
jerry

Reputation: 2611

Add parentheses:

let rec sum n =  
    if n <= 0 then 0
    else if n / 2 * 2 = n then 3 * n + 50 * (sum (n-2))
    else n + 10 * (sum (n-1));;

(* prints 3125 *)
print_int (sum 5);;

Instead of calling sum on n-2 (or n-1), you're calling it on n and subtracting 2 (or 1) from the result. Since the input never changes, it recurses until it overflows the stack.

Upvotes: 5

nlucaroni
nlucaroni

Reputation: 47934

That is because n is not being changed in the recursive call. You'll have to wrap the n-1 and n-2 in parenthesis. You're calling (sum n)-1 instead of sum (n-1).

Upvotes: 5

Related Questions