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
#include<iostream>
#include<string>
#include<cctype>
#include<math.h>
#include<algorithm>
using namespace std;
int main(){
long long decimal(string str,long long radix);
long long find_radix(string str,long long num);
string m,n;
long long tag,radix,result;
cin>>m>>n>>tag>>radix;
if(tag==1){
result = decimal(m,radix);
result = find_radix(n,result);
}else{
result = decimal(n,radix);
result = find_radix(m,result);
}
if(result!=-1){
printf("%lld",result);
}else{
printf("Impossible");
}
return 0;
}
//将radix进制转为10进制,转化进制有可能溢出,溢出就会返回负数。
long long decimal(string str,long long radix){
long long sum = 0,temp = 0;
int index=0;
for(int i = str.length()-1;i >= 0;--i){
if(isdigit(str[i])){
temp = str[i] - '0';
}else{
temp = str[i] - 'a' + 10;
}
sum += temp * pow(radix,index++);
}
return sum;
}
long long find_radix(string str,long long num){
char it = *max_element(str.begin(),str.end());//获取字符串中最大的哪一个数。
long long low = (isdigit(it) ? it - '0':it - 'a' + 10) + 1;//转换成最小进制情况(里面有9不可能是8进制对吧)。
long long high = max(num,low);//进制的最大范围。
while(low<=high){
long long mid = (low + high)/2;
long long temp = decimal(str,mid);
if(temp>num || temp<0){//temp为负数,说明大了
high = mid - 1;
}else if(temp<num){
low = mid + 1;
}else{
return mid;
}
}
return -1;
}
ps:网上参考了几位大神解题,用二分法。