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
题意:给定一个正整数n,编写一个程序找出一个n的非零倍数m,其十进制表示仅包含数字0和1。
注意:n很小的时候可以按照此代码表示,但当N很大的时候,此代码就不能够使用。
#include<stdio.h>
#include<queue>
using namespace std;
void bfs(int x)
{
queue<long long>q;
long long p=1;
q.push(p);
while(!q.empty())
{
p=q.front();
if(p%x==0)
{
printf("%lld\n",p);
return ;
}
q.pop();
q.push(p*10);
q.push(p*10+1);
}
return ;
}
int main()
{
int n;
while(~scanf("%d",&n))
{
if(n==0)
break;
else
bfs(n);
}
return 0;
}
当n的范围是1<n<=1e6时,利用同余 定理进行 剪枝。
代码如下:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<string>
using namespace std;
queue<int>q;
int n;
struct node
{
string s;//string 字符串需要用cout 输出
int num;//余数
};
int book[1000010];//book标记余数是否出现
void bfs()
{
queue<node>q;
node now,nex;
now.s="1";
now.num=1%n;//同余定理
book[now.num]=1;
q.push(now);
while(!q.empty())
{
now=q.front();
q.pop();
if(now.num==0)
{
cout<<now.s<<endl;
return ;
}
nex.s=now.s+'0';
nex.num=(now.num*10)%n;
if(book[nex.num]==0)
{
book[nex.num]=1;
q.push(nex);
}
nex.s=now.s+'1';
nex.num=(now.num*10+1)%n;
if(book[nex.num]==0)
{
book[nex.num]=1;
q.push(nex);
}
}
}
int main()
{
while(~scanf("%d",&n))
{
memset(book,0,sizeof(book));
if(n==1)
printf("%d\n",n);
else
bfs();
}
return 0;
}