【練習賽補題】poj1426 【同餘定理】【有趣~】
阿新 • • 發佈:2019-01-22
Find The Multiple
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.
Time Limit: 1000MS | Memory Limit: 10000K | ||
Total Submissions: 33882 | Accepted: 14173 | 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
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 題意:給你一個int範圍內的正整數n,輸出能夠整除這個正整數n且由01組成的任意一個數x。 思路:同餘定理的應用,所求x是能整除n的數,但是現在x我們未知,只能一步一步從高位到低位遞推出x。 由於x只能由01序列組成,所以我們每次從x的最高位到低位進行查詢的過程中有兩個選擇,取0或者取1,最高位只能為1。 如果我們用bfs模擬除法運算這個過程,用一個數組mod記錄每次的餘數且每次將mod[i]%10+str[i]-'0'對n取餘的餘數入隊,下一次進行運算時,就能通過mod[i-1]得到 mod[i],不過我自己用bfs超時到爆炸,不知道咋回事,就換成了一位大佬的方法,用陣列模擬bfs。
借鑑部落格
#include<stdio.h> #define N 600000 long long mod[N],num[N],n; int j,i; int main() { while(scanf("%lld",&n),n!=0) { i = j = 1; mod[i++] = 1%n;//初始化x的最高位數 while(mod[i-1]!= 0) {//mod[i/2]是上一步取餘的結果 mod[i] = (mod[i/2]*10+i%2)%n;//模擬bfs雙入口搜尋 i++;//解釋:i%2,i為偶數時,模擬+0,i為奇數時,模擬+1 } i--; while(i) { num[j++] = i%2; i/=2; } while(j > 1) {//逆序輸出 printf("%d",num[--j]); } printf("\n"); } return 0; }