描述
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:
142857 *1 = 142857
142857 *2 = 285714
142857 *3 = 428571
142857 *4 = 571428
142857 *5 = 714285
142857 *6 = 857142
输入
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.)
输出
For each input integer, write a line in the output indicating whether or not it is cyclic.
样例输入
142857
142856
142858
01
0588235294117647
样例输出
142857 is cyclic
142856 is not cyclic
142858 is not cyclic
01 is not cyclic
0588235294117647 is cyclic
参考代码//256kB 0ms 2419 B G++ #include <iostream> #include <cstring> using namespace std; //global variable const int N = 100; //functions int iscyclic(char str[]); int judge(char t[],char s[]); void multiply(char t[],int n); void print(char s[],int res); //judge the number int iscyclic(char str[]){ int i,rtn,n = strlen(str); char temp[N]; for(i = 1;i <= n;i ++){ strcpy(temp,str); multiply(temp,i); //std::cout<<"i="<<i<<" "<<temp<<std::endl; if(strlen(temp) > n){ return 0; } rtn = judge(temp,str); if(!rtn){ return 0; } } return 1; } //judge int judge(char t[],char s[]){ int i,len = strlen(t); char temp[N],ctemp[N]; char ch; if(strcmp(t,s) == 0){ return 1; } strcpy(temp,t); for(i = 0;i < len;i ++){ ch = temp[0]; strncpy(ctemp,temp + 1,len - 1); ctemp[len - 1] = ch; ctemp[len] ='\0'; if(strcmp(ctemp,s) == 0){ return 1; } strcpy(temp,ctemp); } return 0; } //multiply void multiply(char t[],int n){ int i,j,k,flag,an[N + 10],ar[N + 10],len = strlen(t); char s[N]; char temp[N]; memset(an,0,sizeof(an)); memset(ar,0,sizeof(ar)); memset(temp,'\0',sizeof(temp)); strcpy(s,t); j = 0; for(i = len - 1;i >= 0;i --){ an[j ++] = s[i] - '0'; } for(i = 0;i < N + 10;i ++){ ar[i] = an[i] * n; } for(i = 0;i < N + 10;i ++){ if(ar[i] >= 10){ ar[i + 1] += ar[i] / 10; } ar[i] = ar[i] % 10; } flag = 0; j = 0; for(i = N + 9;i >= 0;i --){ if(ar[i] > 0 || flag == 1){ s[j ++] = ar[i] + '0'; flag = 1; } } s[j] = '\0'; if(j < len){ k = 0; for(i = j;j < len;j ++){ temp[k ++] = '0'; } temp[k] = '\0'; } strcat(temp,s); strcpy(t,temp); } //print void print(char s[],int res){ if(res){ std::cout<<s<<" is cyclic"; }else{ std::cout<<s<<" is not cyclic"; } std::cout<<std::endl; } int main(){ char str[N]; int res; while(std::cin>>str){ //iscyclic res = iscyclic(str); //print print(str,res); } return 0; }