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.
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
Solution:
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
map<char, int> mp;
void init() {
for (char c = '0'; c <= '9'; c++) {
mp[c] = c-'0';
}
for (char c = 'a'; c <= 'z'; c++) {
mp[c] = c-'a'+10;
}
}
long long convert(string know, long long radix) {
long long num = 0;
for (int i = 0; i < know.length(); i++) {
num = num*radix + mp[know[i]];
}
return num;
}
long long find_radix(string unknow, long long num) {
char min_ch = *max_element(unknow.begin(), unknow.end());
long long l = mp[min_ch] + 1;
long long r = max(num, l);
while (l <= r) {
long long mid = (l+r)/2;
long long unknow_val = convert(unknow, mid);
if (unknow_val == num) {
return mid;
} else if (unknow_val < 0 || unknow_val > num) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return -1;
}
int main() {
init();
string A, B;
long long tag, radix, result;
cin >> A >> B >> tag >> radix;
if (tag == 1) {
result = find_radix(B, convert(A, radix));
} else {
result = find_radix(A, convert(B, radix));
}
if (result == -1) {
cout << "Impossible";
} else {
cout << result;
}
return 0;
}