HDU 1250Hat's Fibonacci(两种方法处理大数)

来源:互联网 发布:数据库从入门到精通 编辑:程序博客网 时间:2024/05/17 07:18

Hat's Fibonacci

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5891    Accepted Submission(s): 1944


Problem Description
A Fibonacci sequence is calculated by adding the previous two members the sequence, with the first two members being both 1.
F(1) = 1, F(2) = 1, F(3) = 1,F(4) = 1, F(n>4) = F(n - 1) + F(n-2) + F(n-3) + F(n-4)
Your task is to take a number as input, and print that Fibonacci number.
 

Input
Each line will contain an integers. Process to end of file.
 

Output
For each case, output the result in a line.
 

Sample Input
100
 

Sample Output
4203968145672990846840663646Note:No generated Fibonacci number in excess of 2005 digits will be in the test data, ie. F(20) = 66526 has 5 digits.
 


                   题目大意:题目的意思就不说了,主要是简单地处理大数。

            解题思路:先是用C++写的处理大数,每次只涉及到两个数相加,直接转换成string,所以位数就取len较大的那位。如果第一位超过了10则直接再最前面加一个1,第一位减去10,string支持直接用"1"+。详见代码。

            题目地址:Hat's Fibonacci

C++代码:
#include<iostream>   #include<string>    using namespace std;  string add(string s1,string s2)  {            int j,l,la,lb;      string ma,mi;      ma=s1;mi=s2;      if(s1.length()<s2.length())        {ma=s2;mi=s1;}      la=ma.size();lb=mi.size();      l=la-1;      for(j=lb-1;j>=0;j--,l--)         ma[l] += mi[j]-'0';       for(j=la-1;j>=1;j--)         if(ma[j]>'9')            {ma[j]-=10;ma[j-1]++;}      if(ma[0]>'9')   //处理第一位超过9了。        {ma[0]-=10;ma='1'+ma;}      return ma;  }  int main(){      int n,i;      string a[8008];      a[1]="1";      a[2]="1";      a[3]="1";      a[4]="1";      for(i=5;i<8008;++i)         a[i]=add(add(add(a[i-1],a[i-2]),a[i-3]),a[i-4]);      while(cin>>n)          cout<<a[n]<<endl;      return 0;       }  

          以后遇到大数的问题,不用那么坑爹的再敲该死的那么长的模板了,直接上JAVA。

JAVA代码:
import java.util.*;import java.math.*;public class Main {     public static void main(String args[])     {       Scanner cin = new Scanner(System.in);       BigInteger res[];       res = new BigInteger[8008];       res[1]=BigInteger.ONE;       res[2]=BigInteger.ONE;       res[3]=BigInteger.ONE;       res[4]=BigInteger.ONE;       for(int i=5;i<=8000;i++)       {       res[i]=res[i-1].add(res[i-2]);       res[i]=res[i].add(res[i-3]);       res[i]=res[i].add(res[i-4]);       }       int p;       while(cin.hasNext())       {       p=cin.nextInt();       System.out.println(res[p]);       }     }}