java菲波那切数列
时间: 2023-11-12 08:57:59 浏览: 95
Java实现菲波那切数列可以使用递归或循环的方式,以下是循环实现的示例代码:
```java
public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
int prev = 0, curr = 1;
for (int i = 2; i <= n; i++) {
int next = prev + curr;
prev = curr;
curr = next;
}
return curr;
}
```
相关问题
菲波那切数列java
以下是两种Java实现斐波那契数列的方法:
1. 递归方法实现斐波那契数列
```java
public class Fibonacci {
public static void main(String[] args) {
int n = 10;
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if (n == 0 || n == 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}
```
2. 使用for循环实现斐波那契数列
```java
public class Fibonacci {
public static void main(String[] args) {
int n = 10;
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int sum = a + b;
a = b;
b = sum;
}
}
}
```
java裴波那契数列
Java中计算斐波那契数列通常使用递归、循环或动态规划等方法。以下是三种常见的实现方式:
1. **递归**(效率较低,不适合大数计算):
```java
public static long fibonacci(int n) {
if (n <= 1) return n;
else return fibonacci(n - 1) + fibonacci(n - 2);
}
```
2. **循环**(更高效,适用于较大数值):
```java
public static long fibonacci(int n) {
if (n <= 1) return n;
long fib = 1, prevFib = 0;
for (int i = 2; i < n; i++) {
long temp = fib;
fib += prevFib;
prevFib = temp;
}
return fib;
}
```
3. **动态规划**(最适合计算,避免了重复计算):
```java
public static long fibonacci(int n) {
int[] fibArray = new int[n + 1];
fibArray = 0;
fibArray = 1;
for (int i = 2; i <= n; i++) {
fibArray[i] = fibArray[i - 1] + fibArray[i - 2];
}
return fibArray[n];
}
```
阅读全文