一、菲波那切数列的定义
- (1)斐波那契数列的定义如下:
- (2)古典问题:有一对兔子,从出生后第 3 个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
- (3)代码实现的功能:
1.打印输出前20位的斐波那契数
2.打印1-100之间的菲波那切数列
3.判断一个数是否是斐波那契数列
4.递归求解斐波那契数列
二、代码实现
package 练习;
public class Feibo {
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* 1.打印输出前20位的斐波那契数
* 2.打印1-100之间的菲波那切数列
* 3.判断一个数是否是斐波那契数列
* 4.递归求解斐波那契数列
*/
forFeibo();
whilefeibo();
Isfeibo(50);
System.out.println("第10位斐波那契数是:" + fib(10));
}
//1.打印输出前20位的斐波那契数
public static void forFeibo() {
long a1 = 1 , a2 = 1 , result = 0;
for(int i = 3; i <= 20 ;i++) {
result = a1 + a2 ;
a1 = a2;
a2 = result ;
System.out.print(result+" ");
}
}
//2.打印1-100之间的菲波那切数列
public static void whilefeibo() {
long a1 = 1 , a2 = 1 , result = 0;
while((a1 + a2) < 100) {
result = a1 + a2 ;
a1 = a2 ;
a2 = result ;
System.out.print(result + " ");
}
}
//3.判断一个数是否是斐波那契数列
public static void Isfeibo(long num) {
boolean result = true;
long a1 = 1;
long a2 = 1;
//判断num是否小于等于1
if(num == a1) {
System.out.println("YES");
}
else if(num < a1){
System.out.println("NO");
}
while(result) {
a1 = a1 + a2;
a2 = a1 + a2;
if(a1 == num || a2 == num) {
result = false ;
System .out.println("YES");
}
else if(num < a2) {
result = false ;
System .out.println("NO");
}
}
}
//递归求解
public static long fib(long n) {
if(n == 1 || n == 2) {
return 1;
}
return fib(n-1) + fib (n-2);
}
}