码迷,mamicode.com
首页 > 其他好文 > 详细

斐波那契数列

时间:2017-01-20 09:48:20      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:short   小兔子   tin   while   rgs   规律   can   exti   new   

/**
*
* 有一对兔子,从出生后第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]+",");
}

}
}

斐波那契数列

标签:short   小兔子   tin   while   rgs   规律   can   exti   new   

原文地址:http://www.cnblogs.com/zkycode/p/6321818.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!