10229-modular Fibonacci
Time limit:3.000 seconds
Http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=115&page=show_ problem&problem=1170
The Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, ...) are defined by the recurrence:
F0 = 0 F1 = 1 Fi = Fi-1 + Fi-2 for i>1
Write a program which calculates Mn = Fn mod 2m for given pair of N and M. 0< =n< and =2147483647 20. Note This a mod B gives the remainder when a was divided by B.
Input and Output
Input consists of several lines specifying a pair of N and M. Output should Mn, one per line.
Sample Input
7
11 6
Sample Output
25
Ideas:
As shown above, use the matrix fast power to fix.
Note: (1<<19) ^2 will be super int, so use long long
Complete code:
/*0.015s*/
#include<cstdio>
#include<cstring>
typedef long long ll;
ll mod;
struct mat
{
ll v[2][2];
mat()
{
memset(v, 0, sizeof(v));
}
} m1;
mat operator * (mat a, mat b)
{
mat c;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
c.v[i][j] = (c.v[i][j] + a.v[i][k] * b.v[k][j]) % mod;
return c;
}
inline mat quickpow(mat a, int k)
{
mat b;
b.v[0][0] = b.v[1][1] = 1;
while (k)
{
if (k & 1)
b = b * a;
k >>= 1;
a = a * a;
}
return b;
}
int main()
{
m1.v[0][0] = m1.v[0][1] = m1.v[1][0] = 1, m1.v[1][1] = 0;
int n, m;
while (~scanf("%d%d", &n, &m))
{
if (n == 0 || m == 0) puts("0");
else
{
mod = 1 << m;
printf("%d\n", quickpow(m1, n - 1).v[0][0]);
}
}
return 0;
}
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/