Search code examples
algorithmrecursionpseudocode

Recursive algorithm for the sum of odd number positive integers


I am expressing the algorithms in pseudo code. I'm just wondering if my design works just as well as the original one displayed below. The algorithm is supposed to compute the sum of n odd positive integers.

This is how the algorithm should look:

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

This is how i designed my algorithm:

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

Solution

  • One small improvement that might help is defining it with tail recursion. Tail recursion happens when the very last thing to execute is the recursive call. To make this tail recursive, use a helper method and pass the running sum as a parameter. I'm pretty sure the pseudo code below is tail recursive since, regardless of the result of the (if odd) check, the final step is the recursive call (the math happens before the recursive call).

    procedure SumOdds(n)
      return SumOddsHelper(n, 0)
    
    procedure SumOddsHelper(n, sum)
      if n = 1 return 1
    
      if n is odd return SumOddsHelper(n-1, sum + n)
      else return SumOddsHelper(n-1, sum)