本文实例讲述了java实现fibonacci算法的方法。分享给大家供大家参考。具体如下:
package com.yenange.test2;
import java.util.scanner;
public class fibonacci {
private static scanner input = new scanner(system.in);
public static void main(string[] args) {
system.out.println("-----------第1种算法------------");
int num1 = 1;
int num2 = 1;
int temp, count;
system.out.println("请输入要查询的是第几个数(>=2):");
count = input.nextint();
system.out.println("第1个数是:1");
system.out.println("第2个数是:1");
for (int i = 3; i <= count; i++) {
temp = num2;
num2 += num1;
system.out.println("第" + i + "个数是:" + num2);
num1 = temp;
}
system.out.println("-----------第2种算法------------");
system.out.println("第" + count + "个数是:" + cal(count));
system.out.println("-----------第3种算法------------");
int[] arr = new int[count];
arr[0] = 1;
arr[1] = 1;
for (int i = 2; i < arr.length; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
system.out.println("第" + (i + 1) + "个数是:" + arr[i]);
}
}
static int cal(int count) {
if (count <= 2) {
return 1;
}
return cal(count - 1) + cal(count - 2);
}
}
希望本文所述对大家的java程序设计有所帮助。
希望与广大网友互动??
点此进行留言吧!