斐波那契数列
Posted 一行代码的事
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了斐波那契数列相关的知识,希望对你有一定的参考价值。
/**
*
* 有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一
* 对兔子,假如兔子都不死,问每个月的兔子总数为多少?
* 1.程序分析:兔子的规律为数列1,1,2,3,5,8,13,21....
* 递归方法:缺点性能极差。优点代码量少。
*/
public class Fibonacci1
{
public int fibo(int i)
{
if(i == 1||i==2)
{
return 1;
}
else
{
return fibo(i-1)+fibo(i-2);
}
}
public static void main(String[] args)
{
Fibonacci1 fibonacci = new Fibonacci1();
int fibo = fibonacci.fibo(1);
int fibo1 = fibonacci.fibo(2);
int fibo2 = fibonacci.fibo(3);
int fibo3 = fibonacci.fibo(4);
int fibo4 = fibonacci.fibo(5);
int fibo5 = fibonacci.fibo(6);
System.out.println(fibo);
System.out.println(fibo1);
System.out.println(fibo2);
System.out.println(fibo3);
System.out.println(fibo4);
System.out.println(fibo5);
}
}
import java.util.Scanner;
/**
* 计算斐波那契数列(Fibonacci)的第n个值
* Created by Abbot on 2017-01-19 0019 11:17:01.
*
*/
public class Fibonacci2
{
public static void main(String[] args)
{
int n = new Scanner(System.in).nextInt();
int n1 = 1;
int n2 = 1;
int sum = 0;
if (n <= 0)
{
System.out.println("参数错误");
return;
}
if (n <= 2)
{
sum = 1;
}
else
{
for(int i = 3; i<=n; i++)
{
sum = n1+n2;
n1 = n2;
n2 = sum;
}
}
System.out.println(sum);
}
}
/**
* Created by Abbot on 2017-01-19 0019 11:23:57.
* 输出Fibonacci数列
*/
public class Fibonacci3
{
public static void main(String[] args)
{
short i = 0,j= 1;
do
{
if(i == 0)
{
System.out.print(j+",");
}
else
{
System.out.print("" + i + "," + j+",");
}
i = (short) (i+j);
j = (short) (i+j);
}while(i>0);
System.out.println();
}
}
/**
* Created by Abbot on 2017-01-19 0019 11:32:34.
* 用一位数组保存Fibonacci序列值
*/
public class Fibonacci4
{
public static void main(String[] args)
{
int n = 25, i;
int fib[] = new int[n];
fib[0] = 0;
fib[1] = 1;
for (i = 2; i < n; i++)
{
fib[i] = fib[i-1]+fib[i-2];
}
for(i= 1;i<fib.length;i++)
{
System.out.print(""+fib[i]+",");
}
}
}
以上是关于斐波那契数列的主要内容,如果未能解决你的问题,请参考以下文章