Problem
A cyclic number is an integer n digits in length which, when multiplied by any integer from 1 to n, yields a ��cycle�� of the digits of the original number. That is, if you consider the number after the last digit to ��wrap around�� back to the first digit, the sequence of digits in both numbers will be the same, though they may start at different positions.
For example, the number 142857 is cyclic, as illustrated by the following table:
Write a program which will determine whether or not numbers are cyclic. The input file is a list of integers from 2 to 60 digits in length. (Note that preceding zeros should not be removed, they are considered part of the number and count in determining n. Thus, ��01�� is a two-digit number, distinct from ��1�� which is a one-digit number.)
Output
For each input integer, write a line in the output indicating whether or not it is cyclic.
Example
Input
142857
142856
142858
01
0588235294117647
Output
142857 is cyclic
142856 is not cyclic
142858 is not cyclic
01 is not cyclic
0588235294117647 is cyclic
自己写完了觉得有些繁琐:
#include <iostream>
using namespace std;
int main()
{
char str[60];
int num[60] = {0};
while(cin>>str)
{
int bit[10] = {0};
int dest[60] = {0};
int round[60] = {0};
int flag = 1;
int len = strlen(str);
int i=0;
for(i=0; i<len; i++)
{
num[i] = str[i] - 48;
dest[i] = num[i];
bit[num[i]] = 1;
}
for(i=1; i<len; i++)
{
int f = 0;
int j = 0;
for(j=len-1; j>=0; j--)
{
dest[j] += num[j];
if(dest[j] > 9)
{
dest[j] = dest[j] % 10;
dest[j-1]++;
}
}
for(j=0; j<len; j++)
round[j] = dest[j];
for(j=0; j<len; j++)
{
int k;
for(k=0; k<len; k++)
{
if(num[k] != round[k])
{
break;
}
}
if(k==len)
{
f = 1;
break;
}
int temp = round[0];
for(k=0; k<len-1; k++)
{
round[k] = round[k+1];
}
round[len-1] = temp;
}
if(f==0)
{
flag = 0;
break;
}
}
if(flag == 1)
{
cout<<str<<" is cyclic"<<endl;
}
else
{
cout<<str<<" is not cyclic"<<endl;
}
}
return 0;
}
遂找了找大神的代码,然后惊呆了:
#include<iostream>
#include<cstdlib>
using namespace std;
int numb[ 62 ];
int main()
{
string a;
while ( cin >> a )
{
int len = a.length()-1;
for ( int i = len ; i >= 0 ; -- i )
numb[ i ] = a[ i ] - '0';
for ( int i = len ; i >= 0 ; -- i )
numb[ i ] *= (len+2);
int flag = 0;
for ( int i = len ; i > 0 ; -- i )
if ( numb[ i ] > 9 )
{
numb[ i-1 ] += numb[ i ]/10;
numb[ i ] %= 10;
if ( numb[ i ] != 9 ) {
flag = 1;break;
}
}
if ( numb[ 0 ] != 9 ) flag = 1;
cout << a;
if ( flag )
cout << " is not cyclic\n";
else
cout << " is cyclic\n";
}
}
其实很简单,数论+高精度:
乘以产生一个循环数的质数(num.length() + 1)时,结果会是一系列的9.如 142857 × 7 = 999999;