Beads of red, blue or green colors are connected together into a circular necklace of n beads ( n < 24 ). If the repetitions that are produced by rotation around the center of the circular necklace or reflection to the axis of symmetry are all neglected, how many different forms of the necklace are there?
The input has several lines, and each line contains the input data n.
-1 denotes the end of the input file.
The output should contain the output data: Number of different forms, in each line correspondent to the input data.
45-1
2139
#include<stdio.h>
#include<cstring>
#include<cmath>
#define ll long long
//要是长整型才行。不然溢出了
ll gcd(ll x,ll y)
{
ll g = y;
ll r = x%y;
while(r != 0)
{
g = r;
r = y%r;
y = g;
}
return g;
}
ll pow_long(ll base, ll exp)
{
ll ans= 1;
while(exp)
{
if(exp & 0x1)
ans *= base;
base *= base;
exp >>= 1;
}
return ans;
}
void polya(long long n)
{
//不动点数 = Σ涂得颜色种类^第k种置换有的轮换的个数
if(n == 0)
{
printf("0\n");
return;
}
long long a = 0;
for(int i = 1; i<=n; i++) //旋转i个珠子情况下每个置换有gcd(i,n)个轮换
{
ll turn_cnt = gcd(n,i);
a += pow_long(3,turn_cnt);
}
//翻转
if(n&0x1) //奇数,n条对称轴,一个置换有1+(n-1)/2个轮换
{
ll turn_cnt = 1+((n-1)/2);
a += n*pow_long(3,turn_cnt);
}
else //偶数,①n/2条对称轴,1个置换有n/2个轮换;②n/2组点构成对称轴,1个置换(n-2)/2+2个轮换
{
ll turn_cnt1 = n/2;
ll turn_cnt2 = (n-2)/2 + 2;
a += (n/2) * (pow_long(3,turn_cnt1) + pow_long(3,turn_cnt2));
}
printf("%lld\n",a/2/n);
}
int main()
{
ll n;
while(scanf("%lld",&n)!=EOF && n!=-1)
{
polya(n);
}
return 0;
}