Recursion overblow

1
2
3
4
5
def fun(p,q):
    if p==0:
        return q
    else:
        return fun(p-1, p+q)

Given the above function what is the value of fun(10000, 9950) ?


The answer is 50014950.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

2 solutions

Claim: f ( p , q ) = q + 1 2 p ( p + 1 ) . f(p,q) = q + \tfrac12 p (p+1). Proof by recursion on p p :

If p = 0 p = 0 then f ( 0 , q ) = q f(0, q) = q is correct.

Assume that the equation is true for some value p p . Then f ( p + 1 , q ) = f ( p , p + 1 + q ) = ( p + 1 + q ) + 1 2 p ( p + 1 ) = q + ( p + 1 ) + 1 2 p ( p + 1 ) = q + 1 2 ( p + 2 ) ( p + 1 ) , f(p+1, q) = f(p, p+1+q) = (p+1+q) + \tfrac12 p(p+1) \\ = q + (p+1) + \tfrac12 p(p+1) = q + \tfrac12(p+2)(p+1), showing that the equation is then also true for p + 1 p + 1 .

Therefore the equation holds for all integer values p 0 p \geq 0 .

The answer, then, is 9950 + 1 2 10 000 10 001 = 50 014 950 . 9950 + \tfrac12\cdot 10\:000\cdot 10\:001 = \boxed{50\:014\:950}.

fun ( p , q ) = q + i = 1 p i = q + p ( p + 1 ) 2 \text{fun}(p,q)=q+\sum_{i=1}^{p}i=q+\frac{p(p+1)}{2}

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...