数论中的算法-循环数

数论中的算法-循环数

浙大OJ中有这样一道题 Round and round we go(1073)

题目如下:

ProblemA 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.)

OutputFor each input integer, write a line in the output indicating whether or not it is cyclic.

ExampleInput142857142856142858010588235294117647Output142857 is cyclic142856 is not cyclic142858 is not cyclic01 is not cyclic0588235294117647 is cyclic

题目的意思很好懂 而且很容易让人联想到大数运算然后查找匹配

不过其实这个题有一个更加投机取巧的方法。

我们来看看所谓循环数是否具有哪些共同性质:

那么如果乘以它的位数加1呢

142857 * 7 = 999999

我们发现这个数字竟然是10^7-1

是否其他循环数也有这样的性质呢,我们来试试

0588235294117647 * 17 = 9999999999999999 = 10^17 - 1

现在我们有理由猜想任何一个循环数都具备这样的性质,据此我们可以写出如下的程序:

int main(){

int i,k,m,temp;

int result[62];

char a[62];

while( scanf("%s",a) != EOF ){

k = strlen(a);

m = 0;

result[k] = 0;

for( i = k - 1 ; i >= 0; i-- )

{

temp = ( k + 1 ) * ( a[i] - '0' ) + result[i+1];

result[i] = temp / 10;

if( temp % 10 != 9){

m = 1;

break;

}

}

if( m )

printf("%s is not cyclic\n",a);

else

printf("%s is cyclic\n",a);

}

return 0;

}

很简洁,数学的力量确实是无比强大啊!也督促了我要好好学习我的专业课了.

相关推荐

七上八下的意思
beat365英超欧冠平台

七上八下的意思

📅 09-30 👁️ 1289
击败陈芋汐,拿到双冠的全红婵能拿多少奖金?奖金用途曝光
如何在京东开店铺详细步骤?要多少钱?
365betappios

如何在京东开店铺详细步骤?要多少钱?

📅 09-23 👁️ 2680
意识到底是什么?我为什么是我?我们的意识,是自然产物还是宇宙的连接?
炉石传说:吾王sol君退出直播圈,最后一次举起我们的双手!
qq号7位数多少钱
beat365英超欧冠平台

qq号7位数多少钱

📅 08-09 👁️ 5803