4423: Necklace
Description
baihacker bought a necklace for his wife on their wedding anniversary.
A necklace with N pearls can be treated as a circle with N points where the
distance between any two adjacent points is the same. His wife wants to color
every point, but there are at most 2 kinds of color. How many different ways
to color the necklace. Two ways are said to be the same iff we rotate one
and obtain the other.
Input
The first line is an integer T that stands for the number of test cases.
Then T line follow and each line is a test case consisted of an integer N.
Constraints:
T is in the range of [0, 4000]
N is in the range of [1, 1000000000]
N is in the range of [1, 1000000], for at least 75% cases.
Output
For each case output the answer modulo 1000000007 in a single line.
Sample Input
6
1
2
3
4
5
20
Sample Output
2
3
4
6
8
52488
Author
baihacker
疯狂地模板题,受不了,比赛的时候连这个定理都没听过,还傻乎乎地想了好久,晕死- -
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
#define ll long long
#define N 32000
ll tot;
ll prime[N+10];
bool isprime[N+10];
ll phi[N+10];
void init()
{
memset(phi,-1,sizeof(phi));
memset(isprime,1,sizeof(isprime));
tot=0;
phi[1]=1;
isprime[0]=isprime[1]=0;
for(ll i=2;i<=N;i++)
{
if(isprime[i])
{
prime[tot++]=i;
phi[i]=i-1;
}
for(ll j=0;j<tot;j++)
{
if(i*prime[j]>N) break;
isprime[i*prime[j]]=0;
if(i%prime[j]==0)
{
phi[i*prime[j]]=phi[i]*prime[j];
break;
}
else
phi[i*prime[j]]=phi[i]*(prime[j]-1);
}
}
}
ll euler(ll n)
{
if(n<=N) return phi[n];
ll ret=n;
for(ll i=0;prime[i]*prime[i]<=n;i++)
{
if(n%prime[i]==0)
{
ret-=ret/prime[i];
while(n%prime[i]==0) n/=prime[i];
}
}
if(n>1) ret-=ret/n;
return ret;
}
ll quickpow(ll a,ll b,ll MOD)
{
a%=MOD;
ll ret=1;
while(b)
{
if(b&1) ret=(ret*a)%MOD;
a=(a*a)%MOD;
b>>=1;
}
return ret;
}
ll exgcd(ll a,ll b,ll& x, ll& y)
{
if(b==0)
{
x=1;
y=0;
return a;
}
ll d=exgcd(b,a%b,y,x);
y-=a/b*x;
return d;
}
ll inv(ll a,ll MOD)
{
ll x,y;
exgcd(a,MOD,x,y);
x=(x%MOD+MOD)%MOD;
return x;
}
void solve(ll n,ll MOD)
{
ll i,t1,t2,ans=0;
for(i=1;i*i<=n;i++)
{
if(n%i==0)
{
if(i*i!=n)
{
t1=euler(n/i)%MOD*quickpow(2,i,MOD);
t2=euler(i)%MOD*quickpow(2,n/i,MOD);
ans=(ans+t1+t2)%MOD;
}
else
ans=(ans+euler(i)*quickpow(2,i,MOD))%MOD;
}
}
ans=ans*inv(n,MOD)%MOD;
printf("%d\n",ans);
}
int main()
{
init();
ll T,n;
ll MOD=1000000007;
scanf("%lld",&T);
while(T--)
{
scanf("%lld",&n);
solve(n,MOD);
}
return 0;
}