本文實例講述了java數學歸納法非遞歸求斐波那契數列的方法。分享給大家供大家參考。具體如下:
Integer能表示的最大值為
2147483647
大概是21.4億,這里沒有考慮溢出情況(當size為983時就會溢出)!
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
|
import java.util.List; import java.util.ArrayList; /** * @author jxqlovejava * 斐波那契數列 */ public class Fibonacci { public static List<Integer> fibonacci( int size) throws Exception { int first = 0 ; int second = 1 ; List<Integer> result = new ArrayList<Integer> (); result.add(first); result.add(second); if (size < 0 ) { throw new Exception( "Illegal argument!" ); } else if (size <= 2 ) { return result.subList( 0 , size); } int next; int count = 2 ; // 當前已經推導出的元素個數 while (count++ < size) { // 基于fib(0)和fib(1)遞推其他元素 next = first + second; first = second; second = next; result.add(next); } return result; } public static void main(String[] args) throws Exception { List<Integer> fibArray = fibonacci( 10 ); for ( int i: fibArray) { System.out.print(i + "\t" ); } } } |
希望本文所述對大家的java程序設計有所幫助。