# Visit of the Great

## 题目描述

The Great Mushroom King descended to the dwarves, but not everyone managed to see him. Only the few chosen ones could see the King.
We know that only $LCM(k^{2^l}+1, k^{2^{l+1}}+1, \ldots, k^{2^r}+1)$ dwarves can see the Great Mushroom King. Numbers $k, l, r$ are chosen by the Great Mushroom King himself in some complicated manner which is unclear to common dwarves.
The dwarven historians decided to document all visits of the Great Mushroom King. For each visit the dwarven historians know three integers $k_i, l_i, r_i$, chosen by the Great Mushroom King for this visit. They also know a prime number $p_i$. Help them to count the remainder of dividing the number of dwarves who can see the King, by number $p_i$, for each visit.

## 算法分析

$g \mid k^{2^n}+1 \Leftrightarrow k^{2^n} \equiv -1 \pmod g$

$\because g \mid k^{2^{n+1}}+1$
$\therefore g \le 2$

## 代码

import std.stdio;

long power(long a, long b, long mod) {
if (b && ! (a % mod)) return 0;
long ret = 1;
while (b) {
if (b & 1) (ret *= a) %= mod;
(a *= a) %= mod, b >>= 1;
}
return ret;
}

long inv(long a, long p) {
return power(a, p - 2, p);
}

int main() {
while (T--) {
long k, l, r, p, q, ans;
readf(" %d %d %d %d", &k, &l, &r, &p), q = p - 1;
if (p == 2) {
if (k & 1) writeln(0); else writeln(1);
continue;
}
ans = (power(k, power(2, l, q) + q, p) + q) % p;
if (! ans) ans = power(2, r - l + 1, p);
else ans = (power(k, power(2, r + 1, q) + q, p) + q) * inv(ans, p) % p;
if (k & 1) (ans *= power((p >> 1) + 1, r - l, p)) %= p;
writeln(ans);
}
return 0;
}


418 I'm a teapot