Round and Round We Go
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
Input
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.
Sample Input
142857
142856
142858
01
0588235294117647
Sample Output
142857 is cyclic
142856 is not cyclic
142858 is not cyclic
01 is not cyclic
0588235294117647 is cyclic
Source
题目类型:简单数学
算法分析:若循环节的位数为6,将上式乘以10 ^ 6得 =>10 ^ 6 / 7 = 142857.142857142857...
=>(10 ^ 6 - 1) / 7 = 142857 => 999999 / 7 = 142857。对于其他数num,如果其位数是n,如果num * (n + 1)得到的结果是n个9,那么这个数就是可循环的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
#include <cstdio> #include <iostream> #include <fstream> #include <cstring> using namespace std; int main() { int i, length; char number[66]; bool cyclic; while (gets (number)) { length = strlen (number); for (i = 0; i < length; i++) number[i] -= '0'; int ans = 0; cyclic = true; for (i = length - 1; i >= 0; i--) { ans += number[i] * (length + 1); if (ans % 10 != 9) { cyclic = false; break; } ans /= 10; } if (ans) cyclic = false; for (i = 1; i < length && cyclic; i++) { cyclic = false; if (number[i] != number[0]) { cyclic = true; break; } } if (cyclic) { for (i = 0; i < length; i++) printf ("%d", number[i]); printf (" is cyclic\n"); } else { for (i = 0; i < length; i++) printf ("%d", number[i]); printf (" is not cyclic\n"); } } return 0; } |
- « 上一篇:poj1045
- poj1050:下一篇 »