斐波纳切递归问题
The Fibonacci numbers Fn are defined recursively as follows:
F0 = 1
F1 = 1
Fn = Fn-1 + Fn-2
1.Write a recursive function, which calculates a Fibonacci number Fn. The function receives n as a parameter.写一个递归函数,计算Fn的数值,函数用n做参数
2. How many times does the function call itself, when n = 5? 当n=5的时候,这个递归函数调用自身的次数是几次?
3. What is the maximum number of parameters n simultaneously allocated on the processor stack.
参数n同时分配到处理器堆栈的最大数量是多少?
第一题这个函数我写出了是:
int f(int n){
if(n==0||n==1)
return 1;
else
return(f(n-2)+f(n-1));
}
但是问题2,3的答案是什么我不确定,答案是多少? 还有3问的是什么意思我不太理解?求助,谢啦
[解决办法]
第二个问题你用一个全局变量就可以了。比如:
#include <stdio.h>int counter = 0;int f(int n){ ++counter; if(n == 0 || n == 1) return 1; else return(f(n-2)+f(n-1));}int main(int argc, char* argv[]){ printf("%s = %d, f was executed %d times\n", "f(5)", f(5), counter); return 0;}
[解决办法]