斐波那契数列
形如 0 ,1,1,2,3,5,8,13...这样的数列称为斐波那契数列
递归实现:
public static int fibonacci(int n) {
if (n <= 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
非递归实现 一:递推方式
public static int fibonacciNormal(int n) {
if (n <= 1) {
return 1;
}
int n0 = 1, n1 = 1, sn = 0;
for (int i = 0; i < n - 1; i++) {
sn = n0 + n1;
n0 = n1;
n1 = sn;
}
return sn;
}
非递归实现 二:数组方式
public static int fibonacci3(int n) {
int a[];
a = new int[n];
a[0] = 1;
a[1] = 2;
int i = 0;
if (n <= 1) {
return 1;
}
for (i = 2; i < n; i++) {
a[i] = a[i - 1] + a[i - 2];
}
return a[i - 1];
}
整体代码:
package 练习;
import java.util.Scanner;
public class fibonacci {
// 递归实现方式
public static int fibonacci(int n) {
if (n <= 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
// 递推实现方式
public static int fibonacciNormal(int n) {
if (n <= 1) {
return 1;
}
int n0 = 1, n1 = 1, sn = 0;
for (int i = 0; i < n - 1; i++) {
sn = n0 + n1;
n0 = n1;
n1 = sn;
}
return sn;
}
//用数组方式
public static int fibonacci3(int n) {
int a[];
a = new int[n];
a[0] = 1;
a[1] = 2;
int i = 0;
if (n <= 1) {
return 1;
}
for (i = 2; i < n; i++) {
a[i] = a[i - 1] + a[i - 2];
}
return a[i - 1];
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please input this fibonacci n:");
int n = in.nextInt(); // 假设输入为大于等于零的整数
System.out.println("递归实现方式");
System.out.println(fibonacci(n));
System.out.println(" 递推实现方式");
System.out.println(fibonacciNormal(n));
System.out.println(" 用数组方式 ");
System.out.println(fibonacci3(n));
}
}
输入值为5 时:
输出结果为: