Find The Multiple(搜索)

本文介绍了一种算法问题,即寻找一个只包含0和1的数,该数能被给定的整数整除。提供了两种解决方案,一种是使用深度优先搜索,另一种则是采用循环的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值