recursion - Recursive algorithm for the sum of odd number positive integers -


i expressing algorithms in pseudo code. i'm wondering if design works original 1 displayed below. algorithm supposed compute sum of n odd positive integers.

this how algorithm should look:

 procedure sumofodds(n:positive integer)     if n = 1        return 1     else        return sumofodds(n-1) + (2n-1) 

this how designed algorithm:

procedure odd(n: positive integer)     if n = 1        return 1     if n % 2 > 0        return n + odd(n-1)    // means n odd     if n % 2 = 0        return 0 + odd(n-1)    // means 

one small improvement might defining tail recursion. tail recursion happens when last thing execute recursive call. make tail recursive, use helper method , pass running sum parameter. i'm pretty sure pseudo code below tail recursive since, regardless of result of (if odd) check, final step recursive call (the math happens before recursive call).

procedure sumodds(n)   return sumoddshelper(n, 0)  procedure sumoddshelper(n, sum)   if n = 1 return 1    if n odd return sumoddshelper(n-1, sum + n)   else return sumoddshelper(n-1, sum) 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -