- Fibonacci II
中文English
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 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 Fn
Example
Example1
Input: n = 9
Output: 34
Example2
Input: n = 30
Output: 2040
Notice
1.0 ≤ n ≤ 1,000,000,000
2.If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros(print Fn mod 10000)
解法1:矩阵快速幂。时间复杂度O(logn)。
代码如下:
struct Matrix {
long long matrix[2][2];
Matrix() {
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
matrix[i][j] = 0;
}
void unit() {
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
if (i == j) matrix[i][j] = 1;
}
Matrix operator * (const Matrix & m) const {
Matrix tmp;
for (int i = 0; i < 2; ++i) {
for (int k = 0; k < 2; ++k) {
if (matrix[i][k] == 0) continue;
for (int j = 0; j < 2; ++j) {
tmp.matrix[i][j] += matrix[i][k] * m.matrix[k][j];
tmp.matrix[i][j] %= 10000;
}
}
}
return tmp;
}
Matrix power(int n) {
Matrix result;
result.unit();
while(n) {
if (n & 0x1) result = result * (*this);
*this = (*this) * (*this);
n /= 2;
}
return result;
}
};
class Solution {
public:
/**
* @param n: an integer
* @return: return a string
*/
string lastFourDigitsOfFn(int n) {
if (n == 0) return "0";
Matrix A;
A.matrix[0][0] = 1;
A.matrix[0][1] = 1;
A.matrix[1][0] = 1;
A.matrix[1][1] = 0;
Matrix m = A.power(n - 1);
string answer;
int p = m.matrix[0][0];
if (p == 0) answer = "0";
else {
for (int i = 0; i < 4; ++i) {
answer = to_string(p % 10) + answer;
p /= 10;
}
}
return answer;
}
};