Given a pair of positive integers, for example, 【PAT (Advanced Level) Practice】1010 Radix (25 分)_进位制 and 【PAT (Advanced Level) Practice】1010 Radix (25 分)_git_02, can this equation 【PAT (Advanced Level) Practice】1010 Radix (25 分)_二分_03 be true? The answer is ​​​yes​​​, if 【PAT (Advanced Level) Practice】1010 Radix (25 分)_进位制 is a decimal number and 【PAT (Advanced Level) Practice】1010 Radix (25 分)_git_02 is a binary number.

Now for any pair of positive integers 【PAT (Advanced Level) Practice】1010 Radix (25 分)_git_06 and 【PAT (Advanced Level) Practice】1010 Radix (25 分)_秦九韶算法_07 , 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 【PAT (Advanced Level) Practice】1010 Radix (25 分)_进位制_08 positive integers:

N1 N2 tag radix

Here ​​N1​​​ and ​​N2​​​ each has no more than 【PAT (Advanced Level) Practice】1010 Radix (25 分)_数学_09 digits. A digit is less than its radix and is chosen from the set { 0-9, ​​​a​​​-​​z​​​ } where 【PAT (Advanced Level) Practice】1010 Radix (25 分)_进位制_10 represent the decimal numbers 【PAT (Advanced Level) Practice】1010 Radix (25 分)_进位制_10, and a-z represent the decimal numbers 【PAT (Advanced Level) Practice】1010 Radix (25 分)_秦九韶算法_12. The last number radix is the radix of ​​​N1​​​ if ​​tag​​​ is 1, or of ​​N2​​​ if ​​tag​​​ is 【PAT (Advanced Level) Practice】1010 Radix (25 分)_二分_13.

Output Specification:
For each test case, print in one line the radix of the other number so that the equation 【PAT (Advanced Level) Practice】1010 Radix (25 分)_进位制_14 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

#include<iostream>

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;
}