1010 Radix

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, az } where 0-9 represent the decimal numbers 0-9, and az 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

#include<iostream>
#include<algorithm>
#include<iomanip>
#include <ctype.h>
#include<string.h>
#include<string>
#include<cstring>
#include<stdio.h>
#include<math.h>
using namespace std;

//思路,将已知进制的数转成10进制,将未知进制的数凑进制转成10进制与已知进制数比较

long long convert(string n, long long radix) {//转10进制
    long long sum = 0;
    for (int i = 0; i < n.length(); i++) {
        if (n[i] <= '9' && n[i] >= 0) {
            sum = sum + (n[i] - '0') * pow(radix, n.length() - (i + 1));
        }
        else if (n[i] <= 'z' && n[i] >= 'a') {
            sum = sum + (n[i] - 'a' + 10) * pow(radix, n.length() - (i + 1));
        }
    }
    return sum;
}

long long find_radix(string n, long long num) {//凑进制//二分查找
    char it = *max_element(n.begin(), n.end());
    long long low = (isdigit(it) ? it - '0' : it - 'a' + 10) + 1;
    long long high = max(num, low);//0 0 情况

    while (low <= high) {
        long long mid = (low + high) / 2;
        long long sum = convert(n, mid);
        if (sum<0||sum > num) {
            high = mid - 1;
        }
        else if (sum < num) {
            low = mid + 1;
        }
        else {
            return mid;
        }
    }
    return -1;
}

int main() {
    string N1;
    string N2;
    int tag;
    long long radix;//tag=1,radix of N1;tag=2,radix of N2
    cin >> N1 >> N2 >> tag >> radix;
    long long ans;
    if (tag == 1) {
        ans = find_radix(N2, convert(N1, radix));
    }
    else
    {
        ans = find_radix(N1, convert(N2, radix));
    }
    if (ans == -1)cout << "Impossible";
    else cout << ans;
}