//哈夫曼编码//同余模定理//二叉树//Find The Multiple------五A

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

这里写图片描述
mod[i]数组里存的是i的二进制形式除n的余数。
比如mod[3]里面存的是3的二进制形式11除n的余数。对于11来说,后面可以添加0或者1,成为110或者111;在十进制中平行的操作就是,3*2+0或者3*2+1,成为6或者7。因为110=11*10+6/2,111=11*10+7/2,所以可以用同余模定理根据mod[3]算出mod[6]和mod[7]。当找到mod[]为0的数时,将其转换成二进制并输出,就是答案了。

#include<stdio.h>

int mod[600001],out[600001];

int main()
{
    int n,i,cnt;
    while(1)
    {
        scanf("%d",&n);
        if(n==0) return 0;
        mod[1]=1%n;
        for(i=2;;i++)
        {
            mod[i]=(mod[i/2]*10+i%2)%n;
            if(mod[i]==0)
                break;
        }
        cnt=0;
        while(i!=0)
        {
            out[++cnt]=i%2;
            i/=2;
        }
        for(i=cnt;i>0;i--)
        {
            printf("%d",out[i]);
        }
        printf("\n");
    }
}

猜你喜欢

转载自blog.csdn.net/lydia_ke/article/details/79348203