Find The Multiple
Time Limit: 1000MS | Memory Limit: 10000K | |||
Total Submissions: 17235 | Accepted: 7013 |
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
import java.util.Scanner;
/**问题请参考http://poj.org/problem?id=1426
* @author rayli
* @date:2014-7-15 下午4:31:58
*
*
*/
public class FindMultiple
{
public static void main(String args[])
{
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int mod[] = new int [524287];//数组设置的小于524287很容易越界
while(n != 0)
{
mod[1] = 1 % n;
int i;
for(i=2; mod[i-1]!=0; i++)//当i的前驱余数不为0
mod[i] = (mod[i/2] * 10 + i % 2) % n;//i%2表示当i为偶数时加0,为奇数时加1.
//i/2是根据二叉树的性质,i/2是i的父母顶点运用了广度优先搜索的性质 。 前一步操作得到的余数 代替 当前步的k值
//(mod[i/2] * 10 + i % 2) % n是同余原理(a*b)%n = (a%n *b%n)%n (a+b)%n= (a%n +b%n)%n
i--;
int pm = 0;
/**
* 当n=6时 最后i=14,通过观察发现,i%2恰好就是 6 的倍数的最低位数字i/2 再令 i%2 ,恰好就是 6 的倍数的 次低位数字。。。
* 循环这个操作,直到i=0,就能得到 6的 01倍数(一个01队列),倒序输出就是所求
* 这样就完成了 *10操作到 %2操作的过渡
*
* 这个是运用0-1 二叉树的从叶子到根的倒序输出
*/
while(i>0)
{
mod[pm++] = i % 2;
i /= 2;
}
/**
* 倒序输出就是所求
*/
while(pm>0)
{
--pm;
System.out.print(mod[pm]);
}
System.out.println();
n = cin.nextInt();
}
}
}