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 descriptiona 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 maid number.
Inputeach line will contain an integers. process to end of file.
Outputfor 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.
Theme: The meaning of the question is not mentioned, mainly to deal with large numbers in a simple way.
Solution: First, we use C ++ to write a large number. Each time we only need to add two numbers and directly convert them into strings. Therefore, the number of digits is the one with a large Len. If the first digit is more than 10, add 1 to the first digit, and subtract 10 from the first digit. String supports "1" +. For details, see the code.
Address: hat's Fibonacci
C ++ code:
# 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 ') // The processing priority exceeds 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 (A [I-1], a [I-2]), A [I-3]), a [I-4]); While (CIN> N) cout <A [n] <Endl; return 0 ;}
In the future, we will encounter a big number problem, so we don't have to worry so much about the damn long template, so we can directly go to Java.
Java code:
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]); } }}