Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.
The teacher remembers that the "very beautiful number" was strictly positive, didn't contain any leading zeroes, had the length of exactlyp decimal digits, and if we move the last digit of the number to the beginning, it grows exactly x times. Besides, the teacher is sure that among all such numbers the "very beautiful number" is minimal possible.
The teachers' office isn't near and the teacher isn't young. But we've passed the test and we deserved the right to see the "very beautiful number". Help to restore the justice, find the "very beautiful number" for us!
The single line contains integers p, x (1 ≤ p ≤ 106, 1 ≤ x ≤ 9).
If the teacher's made a mistake and such number doesn't exist, then print on a single line "Impossible" (without the quotes). Otherwise, print the "very beautiful number" without leading zeroes.
6 5
142857
1 2
Impossible
6 4
102564
Sample 1: 142857·5 = 714285.
Sample 2: The number that consists of a single digit cannot stay what it is when multiplied by 2, thus, the answer to the test sample is "Impossible".
题意:
给出 P(1 ~ 10 ^ 6) 和 N(1 ~ 9),代表 P 位数和乘数 N。需要寻找一个 P 位的数,使 Xp Xp-1 ……X2 X1 * N = X1 Xp Xp-1 …… X3 X2。
思路:
第一位 乘以 N + 进位 = 第二位;
第二位 乘以 N + 进位 = 第三位;
第三位 乘以 N + 进位 = 第四位;
以此类推;
故枚举最末位0 ~ 9 即可,同时比较得出最小值,判断前导0,判断乘积位数和第一位是否等于数的最后一位,最长位数是 10 ^ 6,故用 char 数组存储并且比较即可。
AC:
#include<stdio.h>
#include<string.h>
char num[1000005],sum[1000005];
char min_num[1000005];
int main()
{
int p,x,temp = 0;
scanf("%d%d",&p,&x);
for(int i = 0;i < p;i++) min_num[i] = '9';
min_num[p] = '\0';
for(int i = 0;i <= 9;i++)
{
int CIN = 0;
num[p - 1] = i + '0';
for(int j = p - 1;j >= 0;j--)
{
int k = (num[j] - '0') * x + CIN;
sum[j] = k % 10 + '0';
CIN = k / 10;
if(j) num[j - 1] = sum[j];
}
num[p] = '\0';
sum[p] = '\0';
if(CIN) continue;
if(num[0] == '0') continue;
if(sum[0] != num[p - 1]) continue;
if(strcmp(num,min_num) < 0)
{
strcpy(min_num,num);
temp = 1;
}
}
if(!temp) printf("Impossible\n");
else puts(min_num);
return 0;
}