简体   繁体   English

对C语言的代码片段应用尾递归吗?

[英]Apply Tail Recursion for the piece of code in C language?

The below is a piece of code which uses recursion to find the product of numbers in an array, but i am not getting how to do the same tail recursively any suggestions? 下面是一段代码,它使用递归来查找数组中数字的乘积,但是我没有得到如何递归地做同样的尾巴的任何建议?

  int Product(int a[], int i, int n) 
   {
    return (i >= n) ? 1 : a[i] * Product(a, i + 1, n);
   }

In its current form, your code isn't tail recursive. 在当前形式下,您的代码不是尾部递归。 The recursive call has to be the last instruction in the function, and in your code the multiplication happens after the recursive call. 递归调用必须是函数中的最后一条指令,并且在您的代码中,乘法发生在递归调用之后。 So you have to change the signature to take an accumulator that will hold the product of the numbers so far: 因此,您必须更改签名以使用一个累加器,该累加器将保存到目前为止的数字乘积:

int Product(int a[], int i, int n, int acc) 
{
   return (i >= n) ? 1 : Product(a, i + 1, n, a[i] * acc);
}

For the initial call, you should pass 1 as the accumulator value. 对于初始调用,您应传递1作为累加器值。 Since the tail recursive form isn't very convenient to use, you can separate the function into a helper function and another function with the actual implementation: 由于尾部递归形式使用起来不太方便,因此您可以将函数分为助手函数和实际实现中的另一个函数:

int Product(int a[], int i, int n)
{
    return TailProduct(a, i, n, 1);
}

int TailProduct(int a[], int i, int n, int acc) 
{
   return (i >= n) ? 1 : Product(a, i + 1, n, a[i] * acc);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM