Several implementation methods of the number series in feberale
Fibonacci Series...... This series starts from the third item, and each item is equal to the sum of the first two items.
If F (n) is set to the nth item of the series (n, n + ). The Fibonacci sequence can be summarized as follows:
Simple recursive writing:
long long FibonacciSeq(int n){ if (n < 2) { return n; } return FibonacciSeq(n - 1) + FibonacciSeq(n - 2);}
Non-recursive cycle method:
In this method, only three variables are set, and the results are placed in the third variable of the array by cyclic replacement. Although this method has poor read/write performance, when the value of n is large, it is much more efficient than recursive methods.
long long FibonacciSeq(int n) { long long f[3] = { 0, 1,n }; for (int i = 2; i <=n; i++) { f[2] = f[0] + f[1]; f[0] = f[1]; f[1] = f[2]; } return f[2];}
Another non-recursive method is to create an array with a length of n and save all the traversal results in the series to the array.
long long FibonacciSeq(int n){ long long fib[1000] = { 0, 1 }; for (int i = 2; i <= n; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } long long ret = fib[n]; return ret;}
The above method is not rigorous yet, because the array size is fixed here, if n> 1000 is not good, so the following optimization is performed:
long long FibonacciSeq( int n){ if (n ==0) { return 0; } long long *fib=new long long[n+1]; fib[0] = 0; fib[1] = 1; for (int i = 2;i <=n; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } long long ret = fib[n]; delete[] fib; return ret;}
Or use malloc to open up space:
long long FibonacciSeq(int n){ if (n == 0) { return 0; } long long *fib = (long long *)malloc(sizeof(long long)*(n + 1)); fib[0] = 0; fib[1] = 1; for (int i = 2; i <= n; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } long long ret = fib[n]; free(fib); return ret;}
To use new or malloc to open up space for arrays, check the boundary conditions. Otherwise, the program may crash.
Here is a detailed analysis link of the code when the boundary condition check is not performed: cross-border access of new