poj1426 Find The Multiple

Description

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
这道题最后的答案可以用__int64或者long long储存,所以可以用队列直接进行宽搜,每次*10或者*10+1;第二种方法是用公式(a*b)%n=((a%n)*(b%n))%n;(a+b)%n=(a%n+b%n)%n;用mod[i]储存第i次的余数。那么mod[i]=(mod[i/2]*10+i%2)%n;
代码1:
#include<stdio.h>
#include<string.h>
int mod[911111],a[110];
int main()
{
	int n,i,j,t;
	while(scanf("%d",&n)!=EOF && n!=0)
	{
		if(n==1){
			printf("1
");continue;
		}
		memset(mod,0,sizeof(mod));memset(a,0,sizeof(a));
		mod[1]=1;
		for(i=2;;i++){
			mod[i]=(mod[i/2]*10+i%2)%n;
			if(mod[i]==0)break;
		}
		t=0;
		while(i){       //这里发现最后答案就是把i化为二进制的数
			a[++t]=i%2;
			i=i/2;
		}
		for(i=t;i>=1;i--){
			printf("%d",a[i]);
		}
		printf("
");
	}
	return 0;
} 
代码2:(直接用宽搜)
#include<stdio.h>
#include<string.h>
#define maxn 10000000
int n;
long long q[maxn];


long long bfs()
{
	int front=1,rear=1;
	//memset(q,0,sizeof(q));这里不能清空,否则会超时; 
	q[front]=1;
	while(1)
	{
		long long x=q[front];
		front++;
		if((x*10)%n==0){
		    return x*10;
		}
		if((x*10+1)%n==0){
			return x*10+1;
		}
		q[++rear]=x*10;
		q[++rear]=x*10+1;
	}
}


int main()
{
	int i,j;
	while(scanf("%d",&n)!=EOF && n!=0)
	{
	   printf("%lld
",bfs());
	}
	return 0;
}

原文地址:https://www.cnblogs.com/herumw/p/9464818.html