A sequence S n is defined as:
Where a, b, n, m are positive integers.┌x┐is the ceil of x. For example, ┌3.14┐=4. You are to calculate S n.
You, a top coder, say: So easy!
Input
There are several test cases, each test case in one line contains four positive integers: a, b, n, m. Where 0< a, m < 2 15, (a-1) 2< b < a 2, 0 < b, n < 2 31.The input will finish with the end of file.
Output
For each the case, output an integer S n.
Sample Input
2 3 1 2013
2 3 2 2013
2 2 1 2013
Sample Output
4
14
4
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
#include<map>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long ll;
ll mo = 1e9 + 7;
struct p
{
ll q[2][2];
};
p cheng(p q, p w)
{
p fh;
for (long long a = 0; a < 2; a++)
{
for (long long b = 0; b < 2; b++)
{
fh.q[a][b] = 0;
for (long long c = 0; c < 2; c++)
{
fh.q[a][b] += (q.q[a][c] * w.q[c][b] % mo + mo) % mo;
fh.q[a][b] = (fh.q[a][b] % mo + mo) % mo;
}
}
}
return fh;
}
p ksm(p ds, long long zs)
{
p fs;
for (long long a = 0; a < 2; a++)
{
for (long long b = 0; b < 2; b++)
{
if (a != b)fs.q[a][b] = 0;
else fs.q[a][b] = 1;
}
}
while (zs)
{
if (zs & 1)fs = cheng(fs, ds);
ds = cheng(ds, ds);
zs >>= 1;
}
return fs;
}
int main()
{
long long a, b, n, m;
while (cin >> a >> b >> n >> m)
{
mo = m;
p ds = { { a, b, 1, a } };
ds = ksm(ds, n - 1);
long long aa = a*ds.q[0][0] % m + ds.q[0][1] % m;
long long bb = a*ds.q[1][0] % m + ds.q[1][1] % m;
aa = (aa%m + m) % m;
bb = (bb%m + m) % m;
cout << (2 * aa%m + m) % m << endl;
}
}