奇数正整数之和的递归算法 [英] Recursive algorithm for the sum of odd number positive integers

查看:274
本文介绍了奇数正整数之和的递归算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用伪代码表示算法。我只是想知道我的设计是否和下面显示的原始设计一样好。该算法应该计算出n个奇数正整数的总和。

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.

这就是算法的外观:

 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


推荐答案

可能的一个小改进>帮助是通过尾递归来定义的。当最后要执行的是递归调用时,就会发生尾递归。要使此尾部递归,请使用辅助方法并将运行总和作为参数传递。我很确定下面的伪代码是尾部递归,因为无论(如果是奇数)检查结果如何,最后一步都是递归调用(数学发生在递归调用之前)。

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)

这篇关于奇数正整数之和的递归算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆