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
参考翻译:
给定一对正整数,例如 6 和 110,这个等式 6 = 110 能为真吗?答案是,如果 6 是十进制数,110 是二进制数。yes
现在对于任何一对正整数N1和N2,你的任务是找到一个数的基数,而另一个数的基数被给出。
输入规范:
每个输入文件包含一个测试用例。每个案例占据一行,其中包含 4 个正整数:
N1 N2 tag radix
这里和每个不超过 10 位数字。数字小于其基数,从集合 { 0-9, - } 中选择,其中 0-9 表示十进制数 0-9,- 表示十进制数 10-35。最后一个数字是 if 为 1 或 if 为 2 的基数。N1N2azazradixN1tagN2tag
输出规格:
对于每个测试用例,在一行中打印另一个数字的基数,以便方程 = 为真。如果方程不可能,请打印 .如果解不是唯一的,则输出尽可能小的基数。
、
参考代码:
#include<iostream>
#include<cstring>
#include<string.h>
#include<cmath>
using namespace std;
long long int numxradix(string x, int radix){
long long int numx = 0;
int len = x.size();
for(int i = 0; i < len; i++)
{
if(x[i]-'0' <= 9){
numx += (x[i]-'0')*pow(radix, len-i-1);
}else{
numx += (x[i]-'a'+10)*pow(radix, len-i-1);
}
}
return numx;
}
int num_l(string a){
int b=0;
for(int i=0;i<a.size();i++){
int temp=0;
if(a[i]>='a'&&a[i]<='z') temp=a[i]-'a'+10;
else temp=a[i]-'0';
if(temp>b) b=temp;
}
return b;
}
int main()
{
string n1,n2;
int radix, of;
cin >> n1 >> n2 >> of>> radix;
string x;
string y;
if(of==1){
x=n2;
y=n1;
}else{
x = n1;
y = n2;
}
int left = num_l(x)+1;
long long int right = numxradix(y,radix)+1;
long long int ten_N1 = numxradix(y,radix);
int flag = 0;
int num = 0;
while(right >= left){
long long int mid = (right+left)/2;
long long int ret = numxradix(x,mid);
//cout<<"ret"<<ret <<"left "<<left<<" mid"<<mid<<"right "<<right<<"\n";
if(ret == ten_N1){
num = mid;
right = mid-1;
flag = 1;
}else if(ret > ten_N1 || ret < 0){
right = mid-1;
}else if(ret < ten_N1){
left = mid+1;
}
}
if(flag){
cout<<num<<"\n";
}else
cout<<"Impossible"<<"\n";
return 0;
}