Given a pair of positive integers, for example, and , can this equation be true? The answer is yes
, if is a decimal number and is a binary number.
Now for any pair of positive integers and , 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 positive integers:
N1 N2 tag radix
Here N1
and N2
each has no more than digits. A digit is less than its radix and is chosen from the set { 0-9, a
-z
} where represent the decimal numbers , and a-z represent the decimal numbers . The last number radix is the radix of N1
if tag
is 1, or of N2
if tag
is .
Output Specification:
For each test case, print in one line the radix of the other number so that the equation 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
using namespace std;
typedef long long LL;
string n1, n2;
int tag, radix;
int get(char c){
if('0' <= c && c <= '9') return c - '0';
return c - 'a' + 10;
}
LL calc(string s, LL r){
LL res = 0;
// 秦九韶算法
for(auto c: s){
if((double)res * r + get(c) > 1e16) return 1e18; // 当转换成10进制超出最大范围时,这个进制一定偏大了!
res = res * r + get(c);
}
return res;
}
int main(){
cin >> n1 >> n2 >> tag >> radix;
if(tag == 2) swap(n1, n2);
LL target = calc(n1, radix);
LL l = 0, r = target;
for(auto c: n2) l = max(l, (LL)get(c) + 1);
while(l < r){
LL mid = l + r >> 1;
if(calc(n2, mid) >= target) r = mid;
else l = mid + 1;
}
if(target != calc(n2, l)) puts("Impossible");
else cout << l << endl;
return 0;
}