POJ-1426 Find The Multiple

Find The Multiple
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 31553   Accepted: 13158   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

Source

一道不是數水坑也不是走迷宮的DFS,題意:給一個數,讓你找到一個數字對所給數取模,結果爲0,但是這個數只能由數字0和1構成答案也許不唯一,輸出一個結果即可。

思路:既然尋找數只能由0,1構成,那麼1,10,11,100,110這樣的數字滿足第一個條件,設a=1,那麼滿足條件的數可以表示爲a*10和a*10+1,遞歸就可以把a越滾越大且只由0,1構成,對每個構造出來的數取模檢查,如果結果爲0,輸出結果,退出函數。由於數字可能會很大且爲整數,所以使用unsigned long long類型定義變量。step是爲了限制遞歸深度,超過20之後速度會很慢,但貌似這裏在遞歸到19層之前就能找到結果。

#include<iostream>
#define ull unsigned long long
using namespace std;
int n;
int flag=0;
void dfs(ull a,int step)
{
    if(flag || step==19)
        return ;
    if(a%n==0)
    {
        cout << a << endl;
        flag=1;
        return ;
    }
    else
    {
       dfs(a*10,step+1);
       dfs(a*10+1,step+1);
    }
}
int main()
{
    while(cin >> n && n)
    {
        flag=0;
        dfs(1,0);
    }
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章