Sword refers to the Fibonacci series of Offer
All textbooks of the Fibonacci series are available, and will basically appear in the section of recursion. But it doesn't mean that recursion is the best solution of Fibonacci, but because it can better interpret what recursion is. However, this method is not used in real software development. The biggest benefit of recursion is conciseness, which converts large problems into small ones. It is well understood at a macro level. However, the efficiency of recursion is also worth exploring. Recursion requires the system to keep pushing the stack itself, saving the intermediate amount and status, and calling the function also requires time and space. Therefore, there is a problem with efficiency. In addition, the stack capacity opened by each process is limited. If the stack is too large, overflow may occur. For example, if n = 5000, the loop algorithm can find the correct value, but recursion will lead to stack explosion. Another point is repetitive computing. The principle of recursion is to convert a big problem into a small problem, but overlap may occur when it is converted into a small problem, which leads to a straight decline in efficiency.
We can define an array a [3] = {0, 1}; a [0] = 0; a [1] = 1; when n> = 2 is a loop: a [2] = a [0] + a [1]; a [2] = a [1]; a [1] = a [0]; pay attention to the order of values. 9-degree OJ 10 MS.
#include
#include
using namespace std;long long Feibonacci(int n){ long long a[3]={0,1},i; if(n<=1) return a[n]; for(i=2;i<=n;i++) { a[2]=a[0]+a[1]; a[0]=a[1]; a[1]=a[2]; } return a[2];}int main(){ //freopen("/Users/sanyinchen/Workspaces/oc/conse/B_ali/B_ali/in.txt","r",stdin); int n; while(cin>>n) cout<