UVa 10127/POJ 2551 Ones (模运算&转换思想)

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值