Fibonacci
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 12190 |
|
Accepted: 8651 |
Description
In the Fibonacci integer sequence, f0 = 0, f1 = 1, and fn = fn −1 + fn − 2 for n ≥2. For example, the first ten terms of the Fibonacci sequence is:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
An alternative formula for the Fibonacci sequence is
.
Given an integer n, your goal was to compute the last 4 digits of Fn.
Input
The input test file would contain multiple test cases. Each of the test case consists of a 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 is all zeros, print ' 0 '; Otherwise, omit any leading zeros (i.e., print Fn mod 10000).
Sample Input
099999999991000000000-1
Sample Output
0346266875
#include <cstdio>#include<iostream>#include<vector>#include<assert.h>using namespacestd;Const intMOD = (int) 1e4;structMat {vector<vector<int> >m; Mat () {} mat (intAintb) {m.resize (a); for(intI=0; I<m.size (); i++) {m[i].resize (b); } }}; Matoperator* (Constmat& A,Constmat&b) {assert (a.m[0].size () = =b.m.size ()); Mat C (A.m.size (), b.m[0].size ()); for(intI=0; I<a.m.size (); i++) { for(intj=0; j<b.m[0].size (); J + +) {C.m[i][j]=0; for(intk=0; K<b.m.size (); k++) {C.m[i][j]= (C.m[i][j] + a.m[i][k] * B.m[k][j]% MOD)%MOD; } } } returnC;} Matoperator^ (Mat A,intk) {assert (A.m.size ()= = a.m[0].size ()); Mat C (A.m.size (), a.m.size ()); for(intI=0; I<a.m.size (); i++) { for(intj=0; J<a.m.size (); J + +) {C.m[i][j]= (i==j); } } while(k) {if(k&1) {C= c *A; } A= A *A; K>>=1; } returnC;}intMain () {intN; Mat A (2,2), B (2,1); a.m[0][0]=a.m[1][0]=a.m[0][1]=1; a.m[1][1]=0; b.m[0][0]=1; b.m[1][0]=0; while(SCANF ("%d", &n)! = EOF && n! =-1) { if(n==0) printf ("%d\n", b.m[1][0]); Else if(n==1) printf ("%d\n", b.m[0][0]); Else{Mat ans= (a^ (n1)) *b; printf ("%d\n", ans.m[0][0]); } } return 0;}
POJ 3070--fibonacci "Matrix fast Power"