POJ - 1426 Find The Multiple

Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more than 100 decimal digits.
Input
The input file may contain multiple test cases. Each line contains a value of n (1 <= n <= 200). A line containing a zero terminates the input.
Output
For each value of n in the input print a line containing the corresponding value of m. The decimal representation of m must not contain more than 100 digits. If there are multiple solutions for a given value of n, any one of them is acceptable.
Sample Input
2
6
19
0
Sample Output
10
100100100100100100
111111111111111111
            这是个搜索题。不过一般很难想到TT。

         题意:给一个数,让你找到一个数字对所给数取模,结果为0,但是这个数只能由数字0和1构成答案或许不唯一,输出一个结果即可。不过呢,数据有点大,要用long long int .  既然是搜索,肯定有规律啦。一位一位的确定,比如求被6整除的不为零整数,且整数的每位上是0或1
              从个位,十位,百位。。。一直确定上去(即10%6,11%6,100%6 .......),即每次扩展都在末尾加上0或者1
              首先初始为1,因为倍数的最高位必为1。这就是规律啦。首先要确定最小值1.选两个方向进行搜,一个*10,一个*10+1,找到一个就停止(答案不一定提供的相同,这就有一点难度了,要靠自己判断)。

   还有,这个题用到了同余模定理,(a*b)%n = (a%n *b%n)%n(a+b)%n = (a%n +b%n)%n.这也是为什么用long long int的一个原因。因为范围有限,所以搜到18层时要退出,进行下一个搜索。

#include<stdio.h>
int n,f;
void dfs(long long int m,int step)   //step记录搜索达到的层数
{
    if(f||step>18)return ;        //如果找到一个值,或者层数大于18层要跳出循环,根据f得值确定是否进行下一轮搜索。
    if(m%n==0&&m)
    {
        printf("%lld\n",m);
        f=1;
        return;
    }
    dfs(m*10,step+1);
    dfs(m*10+1,step+1);
}
int main()
{
    while(~scanf("%d",&n)&&n)
    {
        f=0;                    //标记是否找到值
       dfs(1,0);                //m初始为一。
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zitian246/article/details/75577260