Fibonacci Numbers-hdu3117

来源:互联网 发布:水杉 mac 破解 编辑:程序博客网 时间:2024/05/06 21:17

Fibonacci Numbers

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1285    Accepted Submission(s): 543


Problem Description
The Fibonacci sequence is the sequence of numbers such that every element is equal to the sum of the two previous elements, except for the first two elements f0 and f1 which are respectively zero and one.

What is the numerical value of the nth Fibonacci number?
 


 

Input
For each test case, a line will contain an integer i between 0 and 108 inclusively, for which you must compute the ith Fibonacci number fi. Fibonacci numbers get large pretty quickly, so whenever the answer has more than 8 digits, output only the first and last 4 digits of the answer, separating the two parts with an ellipsis (“...”).

There is no special way to denote the end of the of the input, simply stop when the standard input terminates (after the EOF).
 


 

Sample Input
0123453536373839406465
 


 

Sample Output
0112359227465149303522415781739088169632459861023...41551061...77231716...7565

 

思路:

//1.后4位15000次循环一次
//2.前四位用数学公式推导可求
//3.前四位具体推导方法如下:

fib(n)= ([(1+√5)/2] n -[(1-√5)/2]n)√5

fib(n)= [(1+√5)/2] n /√5//当n很大的时候[(1-√5)/2]n)很小,可忽略

log10fib(n)=log10([(1+√5)/2]n/√5)

log10fib(n)=nlog10(1+√5)-nlog102-log10√5

例如log10fib(n)=3.123123

则  10log10fib(n)=103.123123

显然fib(n)=0.123123*1000

只需要求0.123123小数部分前4位即可

 

import java.util.Scanner;public class Main{public static int arr[] = new int[1000000];public static int fib[] = new int[41];public static int T = 0;public static void main(String[] args) {Scanner sc = new Scanner(System.in);arr[1] = arr[2] = 1;//测试后4位循环(15000循环一次)for(int i=3; i<1000000; i++) {arr[i] = (arr[i-1]+arr[i-2])%10000;if(arr[i]==arr[2] && arr[i-1]==arr[1]) {T = i-2;break;}}//fib的前40位fib[1] = fib[2] = 1;for(int i=3; i<41; i++) {fib[i] = fib[i-1]+fib[i-2];}while(sc.hasNextInt()) {int n = sc.nextInt();if(n<40) {System.out.println(fib[n]);} else {double ans;ans = -0.5*Math.log10(5)+n*Math.log10(1+Math.sqrt(5))-n*Math.log10(2);ans -= (int)(ans);ans = Math.pow(10, ans);while(ans < 1000) {ans *= 10;}System.out.print((int)ans+"...");String str = arr[n%T]+"";while(str.length()<4) {str = "0"+str;}System.out.println(str);}}}}


 

 

原创粉丝点击