1010 Radix (25point(s))
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 N
?1
?? and N
?2
?? , 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
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
#define INF 0x3f3f3f3f
#define CLR(a,b) memset(a,b,sizeof(a))
#define PI acos(-1.0)
LL toNum(char c) //转化为阿拉伯数字
{
if (c >= '0' && c <= '9')return c-'0';return c-'a'+10;
}
LL toDecimal(string str,LL radix) //转到十进制
{
LL num = 0;LL ant = 1;for (int i = str.size()-1 ; i >= 0 ; i-- , ant *= radix){
num += ant * toNum(str[i]);if (num < 0 || ant < 0) //需要判断这个,也许进制太大了呢 return -1;}return num;
}
int main()
{
string a,b;int tag,radix;LL l,r,mid;cin >> a >> b >> tag >> radix;if (tag == 2)swap(a,b);LL base = toDecimal(a,radix);l = 2;r = base;for (int i = 0 ; i < b.size() ; i++) //算出最低的进制数 {
l = max(l , toNum(b[i])+1);}while (r >= l) //二分查找第一个大于base的进制数 {
mid = (l+r) >> 1;LL t = toDecimal(b,mid);if (t >= base || t == -1) //-1时太大溢出了 r = mid-1;elsel = mid+1;}if (toDecimal(b,l) == base) //验证一下是否相等 cout << l << endl;elseputs("Impossible");return 0;
}