本文实例讲述了java实现Fibonacci算法的方法。分享给大家供大家参考。具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
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程序设计有所帮助。