分治 + 快速幂
typedef long long ll;
ll fastpow(ll base, ll power, ll mod) {
ll ans = 1;
while (power > 0) {
if (power & 1) ans = ans * base % mod;
power >>= 1;
base = base * base % mod;
}
return ans;
}
/*******************************************************************************
* the sum of : 1 + p^1 + p^2 + ... + p^c
*
*
* c == 0: == 1
*
*
* c is odd: == [1 + ... + p^(c-1)/2] + [p^(c + 1)/2 + ... + p^c]
* == [1 + ... + p^(c-1)/2] + p^(c - 1) * [1 + ... + p^(c-1)/2]
* == [ 1 + p^(c - 1)] * [1 + ... + p^(c-1)/2]
*
*
* c is even: == [1 + ... + p^(c / 2)] + [p^(c / 2 + 1) + ... + p^c]
* == [1 + ... + p^(c / 2)] + p^(c / 2) * [1 + ... + p^(c / 2)]
* == [1 + p^(c / 2)] * [1 + ... + p^(c / 2)]
*/
ll sum(ll p, ll c, ll mod) {
if (c == 0)
return 1;
else if (c & 1) {
return ((1 + fastpow(p, (c + 1) / 2, mod)) * sum(p, (c - 1) / 2, mod)) % mod;
}
else
return ((1 + fastpow(p, c / 2, mod)) * sum(p, c / 2 - 1, mod) + fastpow(p, c, mod)) % mod;
}