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
Post a Comment