java fibonacci Numbers

1599: Fibonacci Numbers

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 53  Solved: 23
[Submit][Status][Web Board]

Description

A Fibonacci sequence is calculated by adding the previous two members of the sequence, with
the rst two members being both 1.
f(1) = 1; f(2) = 1; f(n > 2) = f(n   1) + f(n   2)

Input

Your task is to take a number as input, and print that bonacci number.

Output

print that bonacci number.

Sample Input

100

Sample Output

354224848179261915075
 1 import java.math.BigDecimal;
2 import java.util.Scanner;
3
4 public class fab {
5 /*
6 * 首先用保留字class来申明一个新的类,而且是公共的类
7 */
8
9 public static void main(String args[]) {
10 /*
11 * 在该类中定义了方法main,其中public 表示权限, 公共的,static
12 * 如果一个成员被声明为static,它就能够在它的类的任何对象创建之前 被访问,而不必引用任何对象。你可以将方法和变量都声明为static。
13 * static 成员的最常见的例子是main( ) 。因为在程序开始执行时 必须调用main() ,所以它被声明为static。 void
14 * 是指main函数返回值为空
15 */
16 Scanner cin = new Scanner(System.in);
17 /*
18 * Scanner--控制台输入 Scanner类是JDK5新添加的一个类,主要作用是处理输入流、文件和文本内容等 。
19 */
20 int n, i;
21 BigDecimal f[] = new BigDecimal[6000];
22 /*
23 * 动态初始化    *
24 * 动态初始化,也就是只为数组指定长度,并且在内存中申请空间。动态初始化可以不必和数组的声明放在一起,也可以重新初始化一个初始化的数组。   
25 * 动态初始化的语法格式:数据类型 数组名称[ ] = new 数据类型[长度]
26 */
27 f[1] = BigDecimal.valueOf(1);
28 f[2] = BigDecimal.valueOf(1);
29 /*
30 * 对大数的赋值
31 */
32 for (i = 3; i <= 5000; i++)
33 f[i] = f[i - 1].add(f[i - 2]);
34 while (cin.hasNext()) {
35 /*
36 * 等同于!=EOF
37 */
38 n = cin.nextInt();
39 System.out.println(f[n]);
40
41 }
42 }
43
44 }

posted on 2011-08-13 20:42  more think, more gains  阅读(228)  评论(0编辑  收藏  举报

导航