Find The Multiple
Time Limit: 1000MS | Memory Limit: 10000K | |||
Total Submissions: 35088 | Accepted: 14644 | Special Judge |
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 题意:就是给定一个数,找到一个只由0,1组成的数并且可以整除给定的数 思路:直接一个搜索就可以,操作就有两个,一个是*10,另个是*10+1,这道题深搜广搜都是可以的 方法1:#include <iostream> #include <cstdio> #include <cstring> using namespace std; int n; int solve;//标记量,在递归中,如果solve为1了,说明之前已经找到了符合条件的不用继续递归下去了 void DFS(unsigned long long num,int k){ if(solve==1)return; if(num%n==0){ printf("%llu\n",num); solve = 1; return; } if(k==19)return;//题目要求不超100位,如果没有这句话可能会一直递归下去,直到溢出 //但是为什么前面已经用solve标记了还会继续递归呢,我觉得可能是这里有两个递归,如果solve等于1,返回到solve为零的情况又去下一个递归了而另一个递归可能没有答案 DFS(num*10,k+1);//因为题目要求只能由0,1组成,所以对于寻找的方向就两个乘10 DFS(num*10+1,k+1);//或者乘10+1,然后判断能否整除就停止 } int main(){ while(~scanf("%d",&n)&&n){ solve = 0; DFS(1,0);//深搜从1开始 } return 0; }
方法2:是一种循环代替搜索的思路,而且很巧妙,具体解释看代码注释#include <iostream> #include <cstdio> #include <cstring> using namespace std; long long mod[1000000]; int main(){ int n; while(~scanf("%d",&n)&&n){ int i; for(i = 1;; i++){//这里要从一开始,为什么看下面 mod[i] = mod[i/2]*10+i%2;//这时关键语句,实际上和上一个代码的深搜是一个道理,只不过用循环代替了,很巧妙,我们来分析一下 //因为每次只有两个操作,所以第i个数,应该由第i/2个数*10或者*10+1得到,因为每次都要乘十,所以每次都乘,只不过就是加一或者不加的问题 //这里就巧妙用到下标奇偶性质,奇数模2为1,就相当与加一,而偶数相当于不加,所以下标从1开始是方便的,你可能问开始的两个加一或不加会不会出现零,因为题目要求不能出现 //零,不会,因为第一个是1,第二个发现虽然不加1但是2/2=1了所以第二个元素还是1,所以从下标1开始很神奇! if(mod[i]%n==0){ printf("%lld\n",mod[i]); break; } } } return 0; }