个人一点愚见,有问题还望指出勿喷
特征方程是看过大佬们的结果才知道的,还特意去学习了被忘掉的特征方程.
递归
/**
* 递归计算
* 时间复杂度O(n^2)
* 如果n比较大时会导致假死,因为递归计算太费时间,每次计算次数大致可以参考2的n次方
* @param n 位置
* @return int
*/
private static int fibRecursion(int n) {
if (n < NUM) {
return n;
}
return fibRecursion(n - 1) + fibRecursion(n - 2);
}
for循环
/**
* for循环计算
* 时间复杂度O(n)
*
* @param n 位置
* @return int
*/
private static int fibLoop(int n) {
if (n < NUM) {
return n;
}
int first = 0;
int second = 1;
for (int i = 0; i < n - 1; i++) {
int temp = first + second;
first = second;
second = temp ;
}
return second;
}
while循环
/**
* 循环计算
* 时间复杂度O(n)
*
* @param n 位置
* @return int
*/
private static int fibWileLoop(int n) {
if (n < NUM) {
return n;
}
int first = 0;
int second = 1;
while (n-- > 1) {
second += first;
first = second - first;
}
return second;
}
特征方程
/**
* 特征方程
* 时间复杂度O(1)
* 自测时丢失精度
* @param n 位置
* @return int
*/
private static int fibMath(int n) {
double c = Math.sqrt(5);
return (int) (((Math.pow((1 + c) / 2, n) - Math.pow((1 - c) / 2, n)) / c));
}