1010 Radix (25分)
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<bits/stdc++.h>
using namespace std;
int main()
{
string n1,n2;
int tag;
long long radix;
cin>>n1>>n2>>tag>>radix;
if(tag==2)
swap(n1,n2);
long long sum1=0,sum2=0;
for(int i=0;i<n1.size();i++){
sum1*=radix;
if(n1[i]>='0'&&n1[i]<='9')
sum1+=n1[i]-'0';
else
sum1+=n1[i]-'a'+10;
}//求sum1
int mx=0;//求n2的最大基数
for(int i=0;i<n2.size();i++){
if(n2[i]>='0'&&n2[i]<='9')
mx=max(mx,n2[i]-'0');
else
mx=max(mx,n2[i]-'a'+10);
}
long long l=mx+1;//从n2最大基数开始查找
long long r=max(l,sum1);//这里需注意,有可能n1的和(sum1)都没有n2的基数大
long long mid=0;
while(l<=r){//进行二分查找
mid=(l+r)>>1;
long long temp=0;
for(int i=0;i<n2.size();i++){
temp*=mid;
if(n2[i]>='0'&&n2[i]<='9')
temp+=n2[i]-'0';
else
temp+=n2[i]-'a'+10;
}
if(temp>sum1||temp<0)//溢出判断,temp有可能炸掉long long
r=mid-1;
else if(temp<sum1)
l=mid+1;
else{
cout<<mid;
return 0;
}
}
cout<<"Impossible";//找不到(即不相等)
return 0;
}