简体   繁体   English

将递归函数转换为迭代函数

[英]Convert recursive function to iterative

I have this recursive defined function: 我有这个递归定义的功能:

Function 功能

And I've already implemented it in C++: 而且我已经在C ++中实现了它:

int f_recursive(int n) {
if (n <= 2) {
    return 1;
}
else {
    return ( n * f_recursive(n - 1) - f_recursive(n - 2) );
}

How can I calculate the same function iteratively? 如何迭代计算相同的函数?

For fun, my first attempt. 为了好玩,我第一次尝试。 Can anyone improve? 谁能改善?

#include <iostream>
#include <iomanip>

int f_recursive(int n)
{
    if (n <= 2) {
        return 1;
    }
    else {
        return (n * f_recursive(n - 1) - f_recursive(n - 2));
    }
}

int f_iterative(int n)
{
    int result = 1, result_1 = 1;

    for (int i = 3 ; i <= n ; ++i) {
        int result_2 = result_1;
        result_1 = result;
        result = i * result_1 - result_2;
    }
    return result;
}

int main()
{
    for(int i = 0 ; i < 14 ; ++i) {
        std::cout << std::setw(10) << f_recursive(i) << " " << f_iterative(i) << std::endl;
    }
}

sample output: 样本输出:

         1 1
         1 1
         1 1
         2 2
         7 7
        33 33
       191 191
      1304 1304
     10241 10241
     90865 90865
    898409 898409
   9791634 9791634
 116601199 116601199
1506023953 1506023953

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

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