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.
-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.
4 5 -1
21 39
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
long long gcd(long long a,long long b)
{
if(b==0)return a;
else return gcd(b,a%b);
}
long long po(long long a,long long b)
{
long long ans=1;
while(b)
{
if(b&1)
{
ans=(ans*a);
b--;
}
b/=2;
a=a*a;
}
return ans;
}
int main()
{
long long a,b,c,d,i,j,k,m,n;
while(~scanf("%lld",&m),m!=-1)
{
if(m==0)
{
printf("0\n");
continue;
}
c=0;
for(i=0;i<m;i++)
{
c+=po(3,gcd(i,m));
}
if(m%2!=0)
{
c+=po(3,m/2+1)*m;
}
else
{
c+=po(3,m/2+1)*(m/2)+po(3,m/2)*(m/2);
}
printf("%lld\n",c/(2*m));
}
return 0;
}