10127 - Ones

Time limit: 3.000 seconds

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=13&page=show_problem&problem=1068

http://poj.org/problem?id=2551

Given any integer 0 <= n <= 10000 not divisible by 2 or 5, some multiple of n is a number which in decimal notation is a sequence of 1's. How many digits are in the smallest such a multiple of n?

Sample input


3 7 9901


Output for sample input


3 6 12



1. 从样例说起——

当n=3时,我们发现3*37=111,所以输出3。

当n=7时,我们发现7*15873=111111,所以输出6。

所以最直观的暴力做法是,把n的所有倍数从1往上试。如果发现某个数的每一位都是1,那么就停。但是这么做要用大数。

2. 有没有简单点的方法呢?——

如果我们把问题倒过来,从1、11、111开始,挨个看它们是不是n的倍数,问题就简单多了。

    a(0) = 1 ,  a(i) = a(i-1)*10 +1  

那么

    a(1)=11, a(2)=111, a(3)=1111 ,....

    b(i) =  a(i) % n = (a(i-1)*10 +1) % n = (a(i-1)%n *10 + 1) % n 

    b(i) = (b(i-1) * 10 +1) % n 

然后看b(i)什么时候为0就行。


完整代码:

/*UVa: 0.016s*/
/*POJ: 0ms,164KB*/

#include <cstdio>
using namespace std;

int main()
{
	int n;
	while (~scanf("%d", &n))
	{
		int k = 10 % n, x = 1, count = 1;
		while (x)
		{
			x = k * x + 1;
			x %= n;
			++count;
		}
		printf("%d\n",count);
	}
	return 0;
}