斐波那契数列
来源:互联网 发布:装修公司软件 编辑:程序博客网 时间:2024/06/05 16:12
“斐波那契数列”的两种算法
斐波那契数列有个规律:从第三个数开始,每个数是前两个数之和,比如:
1 1 2 3 5 8 13 21 34 55......
现在通过两种方式(递归与非递归)算数列中第N个值,代码如下:
/**
* 斐波那契数列算法,从第三个数开始,每个数是前两个数之和:1 1 2 3 5 8 13 21 34 55
* 求第N个数的两种算法,分递归和非递归两种
*/
public class Fib {
public static void main(String[] args) {
System.out.println(f(20));
System.out.println(fx(20));
}
//递归方式
public static int f(int n) {
//参数合法性验证
if (n < 1) {
System.out.println("参数必须大于1!");
System.exit(-1);
}
if (n == 1 || n == 2) return 1;
else return f(n - 1) + f(n - 2);
}
//非递归方式
public static int fx(int n) {
//参数合法性验证
if (n < 1) {
System.out.println("参数必须大于1!");
System.exit(-1);
}
//n为1或2时候直接返回值
if (n == 1 || n == 2) return 1;
//n>2时候循环求值
int res = 0;
int a = 1;
int b = 1;
for (int i = 3; i <= n; i++) {
res = a + b;
a = b;
b = res;
}
return res;
}
}
* 斐波那契数列算法,从第三个数开始,每个数是前两个数之和:1 1 2 3 5 8 13 21 34 55
* 求第N个数的两种算法,分递归和非递归两种
*/
public class Fib {
public static void main(String[] args) {
System.out.println(f(20));
System.out.println(fx(20));
}
//递归方式
public static int f(int n) {
//参数合法性验证
if (n < 1) {
System.out.println("参数必须大于1!");
System.exit(-1);
}
if (n == 1 || n == 2) return 1;
else return f(n - 1) + f(n - 2);
}
//非递归方式
public static int fx(int n) {
//参数合法性验证
if (n < 1) {
System.out.println("参数必须大于1!");
System.exit(-1);
}
//n为1或2时候直接返回值
if (n == 1 || n == 2) return 1;
//n>2时候循环求值
int res = 0;
int a = 1;
int b = 1;
for (int i = 3; i <= n; i++) {
res = a + b;
a = b;
b = res;
}
return res;
}
}
0 0
- 斐波那契数列数列计算
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 斐波那契数列
- 2013年Linux“最佳项目”:Ubuntu、Android榜上有名
- Python 程序员必知必会的开发者工具
- Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (一) —— 总览
- Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (二) —— SQLite
- Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (三) —— SharePreferences
- 斐波那契数列
- Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (四) —— ContentProvider
- Android之ContentProvider
- Yii:给CGridView的某列添加操作按钮
- Andorid学习笔记:事件监听合集
- Android学习笔记:注册权限大全
- CSS中调用ttf文件中的字体
- jQuery 密码验证 字母加数字或符号的组合密码,不能单独使用数字、字母或字符
- man stdio