題目描述:
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
4203968145672990846840663646
Note:
No generated Fibonacci number in excess of 2005 digits will be in the test data, ie. F(20) = 66526 has 5 digits.
解題報告:
1:大數求和,上java。其實可以用矩陣快速冪寫,但也沒快多少。
代碼1:
import java.math.BigInteger;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n;
while(scanner.hasNext()){
n = scanner.nextInt();
BigInteger f1 = new BigInteger("1");
BigInteger f2 = new BigInteger("1");
BigInteger f3 = new BigInteger("1");
BigInteger f4 = new BigInteger("1");
if (n <= 4){
System.out.println(1);
continue;
}
BigInteger ans = new BigInteger("0");
for (int i = 5; i <= n; i++) {
ans = f1.add(f2).add(f3).add(f4);
f1 = f2;
f2 = f3;
f3 = f4;
f4 = ans;
}
System.out.println(ans);
}
}
}
代碼2:
import java.math.BigInteger;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
int n = scanner.nextInt();
if(n <= 4){
System.out.println(1);
continue;
}
Node A = new Node();
A = Init(A);
BigInteger ans = Pow(n - 4, A);
System.out.println(ans);
}
}
public static Node Init(Node A){
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
A.num[i][j] = new BigInteger("0");
}
}
for (int i = 0; i < 4; i++) {
A.num[0][i] = new BigInteger("1");
}
A.num[1][0] = new BigInteger("1");
A.num[2][1] = new BigInteger("1");
A.num[3][2] = new BigInteger("1");
return A;
}
public static Node Mul(Node A, Node B){
Node C = new Node();
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
C.num[i][j] = new BigInteger("0");
for (int k = 0; k < 4; k++) {
C.num[i][j] = C.num[i][j].add(A.num[i][k].multiply(B.num[k][j]));
}
}
}
return C;
}
public static BigInteger Pow(int n, Node A){
Node B = new Node();
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
B.num[i][j] = new BigInteger("0");
}
}
for (int i = 0; i < 4; i++) {
B.num[i][0] = new BigInteger("1");
}
while(n > 0){
if(n % 2 == 1)B = Mul(A, B);
A = Mul(A, A);
n = n/2;
}
return B.num[0][0];
}
}
class Node{
public BigInteger num[][] = new BigInteger[4][4];
}