I have this recursive defined function:
And I've already implemented it in 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.