设计Java 程序,利用至少4种方法实现计算Fibonacci数列第n项数值,n由键盘输入。将四种方法整合到一个代码里
时间: 2024-12-14 18:17:15 浏览: 2
递归方法实现斐波那契数列_递归方法实现斐波那契数列_python_源码
设计Java程序来计算Fibonacci数列的第n项,你可以采用以下四种方法:
1. **递归方法**:
```java
public static long fibonacciRecursion(int n) {
if (n <= 0) return 0;
else if (n == 1 || n == 2) return 1;
else return fibonacciRecursion(n - 1) + fibonacciRecursion(n - 2);
}
```
2. **循环迭代法**:
```java
public static long fibonacciIteration(int n) {
if (n <= 0) return 0;
int a = 0, b = 1;
for (int i = 2; i <= n; i++) {
long temp = a;
a = b;
b = temp + b;
}
return a;
}
```
3. **矩阵快速幂法(适合大数计算)**:
```java
public static long fibonacciMatrixPower(int n) {
long[][] fibMatrix = {{1, 1}, {1, 0}};
if (n <= 1) return n;
while (n > 0) {
if ((n & 1) == 1) fibMatrix = matrixMultiply(fibMatrix, fibMatrix);
n >>= 1;
fibMatrix = matrixMultiply(fibMatrix, fibMatrix);
}
return fibMatrix[0][0];
}
private static long[][] matrixMultiply(long[][] a, long[][] b) {
// 实现矩阵乘法
}
```
4. **动态规划存储中间结果**:
```java
public static long fibonacciDynamic(int n) {
if (n <= 0) return 0;
int[] fib = new int[n+1];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
return fib[n];
}
```
将这四个方法整合在一个Java类中,如下所示:
```java
import java.util.Scanner;
public class FibonacciCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入Fibonacci数列的项数n:");
int n = scanner.nextInt();
System.out.println("递归结果: " + fibonacciRecursion(n));
System.out.println("迭代结果: " + fibonacciIteration(n));
System.out.println("矩阵快速幂结果: " + fibonacciMatrixPower(n));
System.out.println("动态规划结果: " + fibonacciDynamic(n));
scanner.close();
}
// ... (以上四种方法的实现)
}
```
阅读全文