如何将以下递归转换为C中的迭代?
示例:
int sum(int n) {
return n < 2 ? n : sum(n-1) + sum(n-2);
}
答案 0 :(得分:2)
直接应用Fibonacci series的定义:
获得1:1的翻译:
int f(int N) {
int fn = N; // Edit: init fn with N
int fn_1 = 1;
int fn_2 = 0;
while (N >= 2) {
fn = fn_1 + fn_2;
fn_2 = fn_1;
fn_1 = fn;
N--;
}
return fn;
}