The Fibonacci sequence of computer algorithm design and analysis
无穷数列1,1,2,3,5,8,13,21,34,55,...,称为Fibonacci数列。关于它的三种方法:
① Simple Variable method
Set four variables, F1, F2, F, I and then combine the Loop completion algorithm (formerly 20 examples)
#include<studio.h>int mian(){int f1,f2,f,i;f1 = 1,f2 = 1;for(i = 1,i <= 20,i++){f = f1 + f2; //传统迭代方法f1 = f2;f2 = f;}printf("%d",&f);return 0;}
Cons: Only the final result F is retained, and the median value is not saved simplified: Replace the For loop inside:
f2 = f1 + f2;f1 = f2 - f1;这样可以减少一个变量,只需要三个变量就可以了。
② Array
A one-dimensional integer array of length 20 can be defined with a for loop completion algorithm
#include<studio.h>int mian(){int f[20],i;for(int i = 0,i < 20,i++){ f[i] = f[i-1] +f[i-2];}printf("%d",&f[20]);return 0;}
Pros: You can save each value of an intermediate result
③ function
public static int fibonacci(int n){if(n <= 1)return 1; //边界条件else return fibonacci(n-1) + fibonacci(n-2); //递归方程}#include<studio.h>void mian(){int n =20;printf("%d",fibonacci(n));return 0;}
Two conditions for using a function: ① recursive equation ② boundary condition
Want to write something simple today-about computer algorithms