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 <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <queue>
#include <string>
using namespace std;
const int N = 1e6+10;
typedef long long LL;
LL gcd(LL a,LL b)
{
return b?gcd(b,a%b):a;
}
LL power(LL x,LL n)
{
LL ans=1;
while(n)
{
if(n&1) ans*=x;
n>>=1;
x*=x;
}
return ans;
}
int main()
{
LL m=3, n;
while(scanf("%lld", &n)!=EOF&&n!=-1)
{
if(n==0)
{
puts("0");
continue;
}
LL cnt=0;
for(int i=1;i<=n;i++) cnt+=power(m,gcd(i,n));
if(n&1) cnt+=(n*power(m,n/2+1));
else cnt+=(n/2)*(power(m,n/2+1)+power(m,n/2));
cnt/=(n*2);
printf("%lld\n",cnt);
}
return 0;
}