public static void testFibonacci1(int n) {
int a = 1, b=1, c = 0;
for (int i = 1; i <= n; i++) {
if (i == 1) {
System.out.println("第" + i + "等于" + a);
}else if (i == 2) {
System.out.println("第" + i + "等于" + b);
}else {
c = a+b;
a = b;
b = c;
System.out.println("第" + i + "等于" + c);
}
}
}
斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368……
特别指出:第0项是0,第1项是第一个1。
这个数列从第三项开始,每一项都等于前两项之和
public class MainClass {
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
public static void main(String[] args) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("Fibonacci of %d is: %d\n",
counter, fibonacci(counter));
}
}
}
以上代码运行输出结果为:
Fibonacci of 0 is: 0
Fibonacci of 1 is: 1
Fibonacci of 2 is: 1
Fibonacci of 3 is: 2
Fibonacci of 4 is: 3
Fibonacci of 5 is: 5
Fibonacci of 6 is: 8
Fibonacci of 7 is: 13
Fibonacci of 8 is: 21
Fibonacci of 9 is: 34
Fibonacci of 10 is: 55
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。