1.13.6
06:循环数
描述
若一个n位的数字串满足下述条件,则称其是循环数(cyclic):将这个数字串视为整数(可能带有前导0),并用任意一个 1 到 n 之间(包含1和n)的整数去乘它时, 会得到一个将原数字串首尾相接后,再在某处断开而得到的新数字串所对应的整数。例如,数字 142857 是循环数,因为:
142857 *1 = 142857
142857 *2 = 285714
142857 *3 = 428571
142857 *4 = 571428
142857 *5 = 714285
142857 *6 = 857142。
请写一个程序判断给定的数是否是循环数。
注意:在此题中,输入数字串允许带前导0,且前导0不能被忽略,例如“01”是两位数字串,而“1”是一位数字串。但将数字串转化为整数做乘法运算或比较运算时,可以忽略前导0。
输入一行,一个长度在 2 到 60 位之间的数字串。输出一个整数,若输入的数字串是循环数,输出1,否则输出0。样例输入
142857
样例输出
1
来源1047
1 //写的很麻烦,有时间研究下更简单的方法 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #define maxn 65 6 using namespace std; 7 bool calculate(int); 8 bool judge(); 9 void add(int len1,int len2); 10 void deal(int,int [],char[]); 11 char str[maxn],s[maxn]; 12 int sum[maxn],sum1[maxn],sum2[maxn],ans[maxn],ans2[maxn],lenans; 13 int main() 14 { 15 int count; 16 gets(str); 17 count=strlen(str); 18 lenans=count; 19 deal(count,sum2,str); 20 for(int i=0;i<count;i++) 21 ans2[i]=sum2[count-1-i]; 22 if(calculate(count)==true) printf("1"); 23 else printf("0"); 24 return 0; 25 } 26 bool calculate(int count) 27 { 28 for(int i=1;i<=count;i++) 29 { 30 add(count,lenans-1); 31 if(judge()==false) return false; 32 } 33 return true; 34 } 35 void add(int len1,int len2) 36 { 37 int x=0,len3=0; 38 while(len3<len1||len3<len2) 39 { 40 sum[len3]+=sum1[len3]+sum2[len3]; 41 x=sum[len3]/10; 42 sum[len3]%=10; 43 sum[len3+1]+=x; 44 len3++; 45 } 46 memset(sum1,0,sizeof(sum1)); 47 memcpy(sum1,sum,sizeof(sum)); 48 memset(sum,0,sizeof(sum)); 49 lenans=len3; 50 } 51 void deal(int count,int a[],char k[]) 52 { 53 memset(a,0,sizeof(a)); 54 for(int i=0;i<count;i++) 55 { 56 a[i]=k[count-1-i]-'0'; 57 } 58 } 59 bool judge() 60 { 61 memset(ans,0,sizeof(ans)); 62 for(int i=0;i<lenans;i++) 63 ans[i]=sum1[lenans-1-i]; 64 for(int i=0;i<lenans;i++) 65 { 66 bool flat=true; 67 int l=i; 68 while(l<lenans+i) 69 { 70 71 if(ans[l%lenans]!=ans2[l-i]) 72 { 73 flat=false; 74 break; 75 } 76 l++; 77 } 78 if(flat==true) return true; 79 } 80 return false; 81 }

浙公网安备 33010602011771号