编程中的数学题

来源:百度知道 编辑:UC知道 时间:2024/05/08 23:45:19
这是题目:
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?
题意是:
输入满足要求的 n ,然后 n 的某倍数是一个完全由1组成的数,要求输出这个完全由1组成的数有几位数

下面是实现的代码:
#include<iostream>
#include<cmath>
using namespace std;

int main()
{
unsigned n, a, total;
while(cin>>n)
{
a = total = 1;
a %= n;
while(a)
{
a = a * 10 + 1;
total++;
a %= n;
}
cout<<total<<endl;
}
return 0;
}
我想知道为什么这样就可以得出结果~~详细加分,谢谢了

做法类似于我们做手工除法.
a开始时是1,以后不断地往后面加1,然后用n去除a.
得出来的模数则与后面的若干个1组成新的被除数.
直到剩下的数能被n除尽,此时1的个数就是答案(最短的位数)
单步调试跟踪a的值应该比较容易明白.