计算第N个斐波那契数

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

计算第N 个斐波那契数
Martyr2项⽬实现——Number 部分的问题求解(2)Fibonacci Sequence Fibonacci Sequence
题⽬描述:
Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number 翻译:
给定正整数N ,编写程序⽣成斐波那契数列的前N 项,或者第N 项。

计算原理:
斐波那契数列{F n }使⽤递推定义:
初值:F 0=0, F 1=1
递推公式:F n =F n −1+F n −2,(n >=2)
根据递推公式,使⽤不动点⽅程x 2−x −1=0可以求出斐波那契数列的通项公式
通项公式:F n =1
√5(ϕn −ψn ),
其中ϕ,ψ为⽅程x 2−x −1=0的两个解。

ϕ=1+√52,ψ=1−ϕ=1−√5
2
``斐波那契数列的矩阵形式
F n +1F n F n F n −1=F n F n −1F n −1F n −21110对应的递推公式为:
F n +1F n F n F n −1=111
0n 算法:1. 第⼀种实现⽅法是递归,因为给定了初值和递推公式,可以直接递归计算。

但是当计算的项数N 很⼤时,可能会导致递归层数过⼤导致栈溢出
⽽且在计算时,有些中间的斐波那契项被计算了多次,重复计算。

实现程序
``
public static long calculateFibonacci(int N){
if(N==0) return 0;
if(N==1) return 1;
return calculateFibonacci(N-1)+calculateFibonacci(N-2);
}
2. 将递归算法改为⾮递归,同时使⽤临时变量来存储计算的中间值。

实现程序
public static String calc1(int N){ //⾮递归算法
if(N<0||N>=10000) return "error: 给定参数N 超出范围[0,10000]";
if(N==0) return "0";
if(N==1) return "1";
BigDecimal f1 = new BigDecimal(0);
BigDecimal f2 = new BigDecimal(1);
(
)()()()()
BigDecimal f = new BigDecimal(1);
for(int i=1;i<N;i++){
f = f2.add(f1);
f1 = f2;
f2 = f;
}
return f.toString();
}
3. 利⽤斐波那契数列的矩阵形式,借助快速幂算法来加快计算矩阵的幂(只有在需要计算的项数很⼤时才有优势)
矩阵的幂快速计算参考博客:
public static long calc2(int N){ //利⽤斐波那契的矩阵形式来计算
if(N==0) return 0;
if(N==1) return 1;
int n = N-1;
long[][] res = {{1,1},{1,0}};
res = pow_matrix(res,N-1);
return res[0][0];
}
private static long[][] pow_matrix(long[][] A,int N){ //定义的⼆阶矩阵快速幂算法
int[] stack = new int[N];
long[][] res = A;
int top=-1;
while(N>=1){
stack[++top] = N;
N/=2;
}
while(top!=-1){
if(stack[top] == 1) res = A;
else if(stack[top]%2==0) //取出的为偶数
res = matrixMultiply(res,res);
else{
res = matrixMultiply(res,res);
res = matrixMultiply(res,A);
}
top--;
}
return res;
}
private static long[][] matrixMultiply(long[][] A,long[][] B){ //⼆阶矩阵乘法
long[][] result = new long[2][2];
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
result[i][j] +=A[i][k]*B[k][j];
return result;
}
递归算法与⾮递归算法的运⾏时间⽐较:
递归算法执⾏的时间:536
斐波那契数列第40项数值:102334155
⾮递归算法执⾏的时间:0
斐波那契数列第40项数值:102334155
⾮递归与矩阵算法运⾏时间⽐较:
------------------------利⽤不同的⽅法计算第90项斐波那契数--------------------
⾮递归算法执⾏的时间:1 ms
斐波那契数列第90项数值:2880067194370816120
基于矩阵快速幂的斐波那契算法执⾏的时间:0 ms
斐波那契数列第90项数值:2880067194370816120
Processing math: 100%。

相关文档
最新文档