​http://www.elijahqi.win/archives/2942​​​
As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that

for some function . (This equation should hold for any integer x in the range 0 to p - 1, inclusive.)

It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7.

Input
The input consists of two space-separated integers p and k (3 ≤ p ≤ 1 000 000, 0 ≤ k ≤ p - 1) on a single line. It is guaranteed that p is an odd prime number.

Output
Print a single integer, the number of distinct functions f modulo 109 + 7.

Examples
Input

Copy
3 2
Output
3
Input

Copy
5 4
Output
25
Note
In the first sample, p = 3 and k = 2. The following functions work:

f(0) = 0, f(1) = 1, f(2) = 2.
f(0) = 0, f(1) = 2, f(2) = 1.
f(0) = f(1) = f(2) = 0.
非常有趣的一个数学题 感觉非常好玩就来研究了下

f(kx%p)=kf(x)%p给出这样一个方程求集合A—>B的映射有几种情况 两个集合都是0~p-1的

那么可以知道k=0的时候 除了为0的情况其他都是随便对应p^(p-1)

k=1是全部都可以随便对应p^p

反之我们一定可以找一个循环节出来k^m一定会随着m增大在%p意义下重新变成相同的一个序列 那么根据费马小定理可知道x^(p-1)≡1(mod p)p为质数 这个m一定是p-1的因子

每个环起始位置p种可能一共(p-1)/m个环 所以方案数是p^((p-1)/m)

好啦不玩了辣鸡蒟蒻elijahqi该睡觉了..

#include<cstdio>
#include<cctype>
#include<algorithm>
#define ll long long
using namespace std;
inline char gc(){
static char now[1<<16],*S,*T;
if (T==S){T=(S=now)+fread(now,1,1<<16,stdin);if (T==S) return EOF;}
return *S++;
}
inline int read(){
int x=0,f=1;char ch=gc();
while(!isdigit(ch)) {if(ch=='-') f=-1;ch=gc();}
while(isdigit(ch)) x=x*10+ch-'0',ch=gc();
return x*f;
}
const int mod=1e9+7;
int p,k;
inline int ksm(ll b,int t){
ll tmp=1;for (;t;b=b*b%mod,t>>=1) if (t&1) tmp=tmp*b%mod;return tmp;
}
int main(){
freopen("cf603b.in","r",stdin);
p=read();k=read();
if (!k) {printf("%d\n",ksm(p,p-1));return 0;}
if (k==1) {printf("%d\n",ksm(p,p));return 0;}
ll tmp=1;int cnt=1;
for (int i=1;i<=p;++i) {tmp*=k,tmp%=p;if (tmp==1) break;++cnt;}
printf("%d\n",ksm(p,(p-1)/cnt));
return 0;
}