题目
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 N1and N2, your task is to find the radix of one number while that of the other is given.
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 and N2 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, and a-z represent the decimal numbers 10-35. The last number radix is the radix of N1 if tag is 1, or of N2 if tag is 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, print Impossible. 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
思路
统一把已知进制的数视为n1,待求解的数视为n2,处理方法是若tag==2,交换n1、n2。
接下来比较二者10进制的值。先将n1转为10进制,接下来遍历n2的radix,当转换值与n1的相等时即为所求。
一开始从2~36遍历n2的radix,结果许多测试点未通过,上网求解,发现神坑很多。
需要注意的坑:
- n1、n2最大值可能是35^11 -1 = 96549157373046880(10进制) = 0x15702F274957060(16进制),二进制60位,需用long long表示,用int会溢出;
- radix的范围不是2~36。下界为各位最大值+1,最小可以取到1,例如输入0 0 1 2应该输出1;最大可以取到和n1、n2一样大,例如输入96549157373046880 10 1 10,输出应该是96549157373046880。
- 上界如此大,从头遍历的话会超时。需用二分法,将计算规模缩小到logN,N=96549157373046880时,约等于56次(logN威力巨大)。
- 当radix取到极大的值时,拿它计算转化出来的数就可能溢出了,long long也装不下。例如radix=35^11 -1,n2=100时,n2表示的值就已经达到(35 ^ 11 -1) ^ 2。可怕……。这时需要加一个溢出判断,即转换结果是否小于0,若小于0说明进制取的太大了,将上界缩小到mid-1。
代码
#include <iostream>
#include <cctype>
using namespace std;
//将字符串存储的数字s,按radix进制转化为10进制
long long str2int(string s, long long radix){
long long value = 0;
long long multiplier = 1;
for (int i=s.size()-1; i>=0; i--){
int d = isalpha(s[i]) ? s[i]-87 : s[i]-48;
value += (d * multiplier);
multiplier *= radix;
}
return value;
}
int main(){
string n1, n2;
int tag;
long long radix;
cin >> n1 >> n2 >> tag >> radix;
if (tag==2){//统一把已知进制的数视为n1,待求解的数视为n2
swap(n1, n2);
}
long long value = str2int(n1, radix);//求出n1的十进制值
//初始化n2 radix的下界,为各位最大值+1,可能取到1
long long l = 1;
for (int i=0; i<n2.size(); i++){
int d = isalpha(n2[i]) ? n2[i]-87 : n2[i]-48;
if (d >= l){
l = d + 1;
}
}
//初始化n2 radix的上界,最大为value;当n1只有1位数字时,value可能比下界小,此时应取下界的值
long long r = value>l ? value : l;
//二分法找n2的radix
long long mid = 1;
bool flag = false;
while (l <= r){
mid = (l + r) / 2;
long long temp = str2int(n2, mid);
if (temp == value){
flag = true;
break;
}
else if (temp>value || temp<0){ //mid值很大时,返回的temp可能溢出,变成负数
r = mid - 1;
}
else {
l = mid + 1;
}
}
if (flag){
cout << mid << endl;
}
else {
cout << "Impossible" << endl;
}
return 0;
}