POJ 3070 Fibonacci
作者:互联网
题目描述:
In the Fibonacci integer sequence, , , and for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
An alternative formula for the Fibonacci sequence is
.
Given an integer n, your goal is to compute the last 4 digits of .
Input
The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.
Output
For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).
Sample Input
0
9
999999999
1000000000
-1
Sample Output
0
34
626
6875
Hint
As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by
.
Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:
题目大意
求斐波那契第n项。
解题报告:
1:矩阵已列出,直接套模板就行了。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
const ll N = 2;
const ll mod = 10000;
struct matrix{
ll num[N][N];
}A, B;
void init(){
memset(A.num, 0, sizeof(A.num));
memset(B.num, 0, sizeof(B.num));
A.num[0][0] = A.num[0][1] = A.num[1][0] = 1;
}
matrix mul(matrix AA, matrix BB){
matrix C;
memset(C.num, 0, sizeof(C.num));
for(ll i=0; i<N; ++i){
for(ll j=0; j<N; ++j){
for(ll k=0; k<N; ++k){
C.num[i][j] += AA.num[i][k]*BB.num[k][j];
C.num[i][j] %= mod;
}
}
}
return C;
}
ll Pow(ll n){
B.num[0][0] = 1, B.num[1][0] = 0;
while(n){
if(n&1)B = mul(A, B);
n >>= 1, A = mul(A, A);
}
return B.num[0][0]%mod;
}
int main(){
ll n;
while(~scanf("%lld", &n) && n != -1){
init();
if(n == 0){
printf("0\n");
continue;
}
printf("%lld\n", Pow(n-1));
}
return 0;
}
baronLJ 发布了149 篇原创文章 · 获赞 4 · 访问量 1万+ 私信 关注
标签:matrix,ll,3070,num,POJ,Fibonacci,test,include 来源: https://blog.csdn.net/jun_____/article/details/104072594