poj1426

題目名稱:Find The Multiple

題目鏈接:http://poj.org/problem?id=1426


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


題意:給出一個整數n,(1 <= n <= 200)。求出任意一個它的倍數m,要求m必須只由十進制的'0'或'1'組成。


思路:bfs+同餘模,因爲會出現大數問題,所以用同餘模可以解決,


代碼如下:

#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
int n;
struct Node  //將該數表示二進制時記爲x,該數表示十進制時記爲mod
{
    int x,mod;
};
int a[1000000];
queue<Node> q;
int bfs()
{
    while(!q.empty())
        q.pop();
    Node now;
    now.x=1;
    now.mod=1;
    q.push(now);
    while(!q.empty())
    {
        Node d=q.front();
        q.pop();
        Node tmp;
        tmp.x=d.x<<1;
        tmp.mod=d.mod*10%n;
        q.push(tmp);
        if(tmp.mod==0)
            return tmp.x;
        tmp.x=(d.x<<1)+1;
        tmp.mod=(d.mod*10+1)%n;
        q.push(tmp);
        if(tmp.mod==0)
            return tmp.x;
    }
}
int main()
{

    while(scanf("%d",&n)!=EOF)
    {
        int i;
        if(n==0)
            break;
  /*      a[1]=1%n;
        for(i=2;a[i-1]!=0;i++)
            a[i]=(a[i>>1]*10+i%2)%n;   //把二進制取模的結果存在數組裏,下標的二進制是要求的十進制
        i--;*/
        int s=0;
        i=bfs();
        while(i)    //把*10操作轉化爲%2操作,逆向求倍數的每一位數字
        {
            a[s++]=i%2;
            i=i>>1;
        }
        while(s)
            printf("%d",a[--s]);
        printf("\n");
    }
    return 0;
}


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