题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1889
题意:
给出一个不能被 2 和 5 整除的整数 n (0 <= n <= 10000),它的某个倍数用 10 进制表示全部是 1 组成。问符合这个条件的倍数数字由多少个 1 组成。
例如:n = 7 时, 7 * 15873 = 111111;包含 6 个 1,因此结果为 6。
分析:可以很明显的看到,该体产生的数字已经远超过整型类型表达的范围。因此不能试图用整型去寻找该倍数。根据题目,我们只需要确定存在这样一个数字,由 m 个 1 组成,它能被 n 整除。因此只需要试验 m 的值,从 1 开始逐渐增加,直到找到第一个可以被 n 整除的数字为止。我们只需要考虑该数字除以 n 的余数即可(即 mod n)。假设 m 时余数为 remain,容易得出 m = m + 1 时,余数为 (remain * 10 + 1) mod n;
代码:
#include <iostream>
#include<cstdio>
using namespace std;
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int remain=1%n;
int m=1;
while(remain!=0)
{
remain=(remain*10+1)%n;
m++;
}
printf("%d\n",m);
}
return 0;
}