FibonacciTime
limit:MS
Memory Limit:65536KB
64bit IO Format:%i64d &%i64u SubmitStatusPracticePOJ 3070Appoint Description:System Crawler (2015-02-28)
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
Hint
As a reminder, matrix multiplication is associative, and the product of the A/2x2 matrices is given by
.
Also, note that raising any 2×2 matrix to the 0th power gives the identity matrix:
.
Test instructions: Test instructions: Find the result of the nth Fibonacci number mod (m) when N=-1, break. where n (where 0≤n≤1,000,000,000), m=10000;
Idea: The conventional method definitely timed out, the problem learned to use a matrix to quickly power the Fibonacci. Such as:
A = f (n-1), B = f (N-2), so that the n power of the constructed matrix multiplied by the initial matrix results in the result.
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include < iostream> #include <algorithm> #include <set> #include <map> #include <queue>using namespace std;const int inf=0x3f3f3f3f;const int mod=10000;struct node{int mp[3][3];} Init,res;struct node Mult (struct node x,struct node y) {struct node tmp; int i,j,k; for (i=0;i<2;i++) for (j=0;j<2;j++) {tmp.mp[i][j]=0; for (k=0;k<2;k++) {tmp.mp[i][j]= (tmp.mp[i][j]+x.mp[i][k]*y.mp[k][j])%mod; }} return tmp;} struct Node expo (struct node x, int k) {int i,j; struct node tmp; for (i=0;i<2;i++) for (j=0;j<2;j++) {if (i==j) tmp.mp[i][j]=1; else tmp.mp[i][j]=0; } while (k) {if (k&1) Tmp=mult (tmp,x); X=mult (X,X); k>>=1; } return TMP; int main () {inT k; while (~SCANF ("%d", &k)} {if (k==-1) break; Init.mp[0][0]=1; Init.mp[0][1]=1; Init.mp[1][0]=1; init.mp[1][1]=0; Res=expo (INIT,K); printf ("%d\n", res.mp[0][1]); } return 0;}
POJ 3070-fibonacci (Matrix fast Power for Fibonacci sequences)