Given a pair of positive integers, for example, 6 and 110, can this equation 6 = 110 be true? The answer is
yes
, if 6 is a decimal number and 110 is a binary number.Now for any pair of positive integers N1 and N2, your task is to find the radix of one number while that of the other is given.
给定一对正整数,例如6和110,这个方程6=110是否为真?答案是肯定的,如果6是十进制数,110是二进制数。对于任意一对正整数N1和N2,你的任务是找到一个数的基数,而另一个数字的基数是给定的。
Input Specification:
Each input file contains one test case. Each case occupies a line which contains 4 positive integers:
N1 N2 tag radix
Here
N1
andN2
each has no more than 10 digits. A digit is less than its radix and is chosen from the set { 0-9,a
-z
} where 0-9 represent the decimal numbers 0-9, anda
-z
represent the decimal numbers 10-35. The last numberradix
is the radix ofN1
iftag
is 1, or ofN2
iftag
is 2.这里N1和N2各有10位数。数字小于其基数,并从集合{0-9,a-z}中选择,其中0-9表示数0-9,a-z表示数10-35。如果标签是1,那么最后基数就是N1的基,2的话就是N2的基是2。
Output Specification:
For each test case, print in one line the radix of the other number so that the equation
N1
=N2
is true. If the equation is impossible, printImpossible
. If the solution is not unique, output the smallest possible radix.Sample Input 1:
6 110 1 10
Sample Output 1:
2
Sample Input 2:
1 ab 1 2
Sample Output 2:
Impossible
#include<iostream>
#include<algorithm>///max_element函数
#include<cmath>///pow函数
typedef long long ll;///方便书写
using namespace std;
///查找与已知进制数相等的未知进制数的进制
///遍历势必会超时,所以用二分呐~
ll convert(string n, ll radix)
{
///n为已知进制为radix的数,将其转化为十进制longlong型
ll sum = 0;
int index = 0, temp ;
for (auto it = n.rbegin(); it != n.rend(); it++)
{///逆序转化
temp = isdigit(*it) ? *it - '0' : *it - 'a' + 10;
///*it指向一个字符,如果该字符是数字,是就变成数字(0~9),是字母的话就变成字母对应的数字(10~35)
///变成数字的目的是进行进制转换
///temp是从最后一个数往前
sum += temp * pow(radix, index++);///利用pow函数,幂次从0开始递增(radix^index)
///如110转十进制:0*2^0+1*2^1+1*2^2=6
}
return sum;///十进制longlong型
}
///很重要的一点!!!进制越大,转化为十进制的结果越大
ll find_radix(string n, ll num)
{///二分未知进制的数,将其转化为十进制long long型,再判断与已知进制数的十进制的大小
///num为转化完成的已知进制的数的十进制数
char it = *max_element(n.begin(), n.end());///迭代器返回n中最大的字符
ll low = (isdigit(it) ? it - '0' : it - 'a' + 10) + 1;
///判断该字符是否为数字,是就变成数字(0~9),是字母的话就变成字母对应的数字(10~35)
ll high = max(num, low);
///对于基数范围,可以遍历位置数的每一位,得到单个位的最大数,
///不管是几进制,基数肯定比这个最大值大,这是基数的取值下限。
///然后,对于已知数,基数肯定不可能大于已知数,这是基数的取值上限。
while (low <= high)
{
///开始二分
ll mid = (low + high) / 2;///中值进制
ll t = convert(n, mid);///未知进制的数变成mid进制
if (t < 0 || t > num) high = mid - 1;///中值溢出(<0)肯定是大了,找小进制区间(左区间)
else if (t == num) return mid;///相等就返回进制值
else low = mid + 1;///找右区间(大进制区间)
}
return -1;///解不存在
}
int main()
{
string n1, n2;///输入为字符串是因为10~35是用字母表示的
ll tag, radix = 0, result_radix;
cin >> n1 >> n2 >> tag >> radix;
result_radix = tag == 1 ? find_radix(n2, convert(n1, radix)):find_radix(n1, convert(n2, radix));
///tag为1,传入未知进制的n2和转为10进制的n1否则就反过来~~把结果赋给result_index
if (result_radix != -1)
printf("%lld", result_radix);
else
printf("Impossible");
}