Description
In the Fibonacci integer sequence,F0 = 0,F1 = 1, andFN=FN− 1 +FN−2N≥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 integerN, Your goal is to compute the last 4 digitsFN.
Hint
As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given
.
Also, note that raising any 2 × 2 matrix to The 0th power gives the identity matrix:
.
-
Input
-
The input test file will contain in 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
-
091000000000-1
-
Sample output
-
0346875
Question]
The Fibonacci series can be obtained using matrices.
When the last few digits of a very large Fibonacci number are obtained, we can use the Matrix to quickly solve the problem.
# Include <iostream> # include <stdio. h> # include <vector> # include <string. h> using namespace STD; typedef vector <int> VEC; typedef vector <VEC> MAT; const int n = 10000; mat mul (MAT a, mat B) // calculate the product of the two matrices {mat C (. size (), VEC (B [0]. size (); For (INT I = 0; I <. size (); I ++) {for (int K = 0; k <B. size (); k ++) {for (Int J = 0; j <B [0]. size (); j ++) {c [I] [J] = (C [I] [J] + A [I] [k] * B [k] [J]) % N ;}}} return C;} mat get_ans (MAT a, int N) // The Rapid power of the matrix {Ma T B (. size (), VEC (. size (); For (INT I = 0; I <. size (); I ++) {B [I] [I] = 1;} while (n> 0) {If (N & 1) B = MUL (B, a); A = MUL (a, a); N >>=1;} return B;} int main () {long int N; while (~ Scanf ("% LLD", & N), N> = 0) {If (n =-1) break; MAT a (2, VEC (2 )); A [0] [0] = 1, a [0] [1] = 1; A [1] [0] = 1, a [1] [1] = 0; A = get_ans (A, n); printf ("% d \ n", a [1] [0]);} return 0 ;}
Fibonacci series (ii) _ Rapid power of Matrix