3

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?

1
  • always check your recursion carefully: initialisation, stopping condition and recurse. Stack overflow during evaluation means that your stopping condition is wrong! Commented Jun 4, 2013 at 18:33

2 Answers 2

5

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).

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.