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
已知两个数(最多有10位),其中一个数的基数,求使两个数相等的另一个数的基数,
long long conver_radix(long long radix,string vs) {
long long ans = 0,index=0;
for(int i=vs.length()-1; i>=0; i--) {
int temp=isdigit(vs[i])?vs[i]-'0':vs[i]-'a'+10;
ans += temp*pow(radix,index++);
}
return ans;
}
#include <iostream>
#include <cmath>
#include <string>
#include <algorithm>
#include <climits>
using namespace std;
long long conver_radix(long long radix,string vs) {
long long ans = 0,index=0;
for(int i=vs.length()-1; i>=0; i--) {
int temp=isdigit(vs[i])?vs[i]-'0':vs[i]-'a'+10;
ans += temp*pow(radix,index++);
}
return ans;
}
int main(int argc,char * argv[]) {
string N1,N2,w,y;
long long tag,radix;
cin>>N1>>N2>>tag>>radix;
if(tag==1) w=N2,y=N1;
else w=N1,y=N2;
long long ys=conver_radix(radix,y); //已知进制数的十进制
char it = *max_element(w.begin(),w.end());
long long low=(isdigit(it)?it-'0':it-'a'+10)+1; //进制下界:找到最大数字+1, 若最大数字为9,那么最小进制应该为10
long long high=max(low,ys); //进制上界:基准十进制数与下界取较大,INT_MAX不对,第一个测试点错误
long long m = low+((high-low)>>1);
while(low<=high) {// 二分查找
m = low+((high-low)>>1);
// m作为基数,转换数字到十进制,与另外一个数字十进制比较
long long ws = conver_radix(m,w);
if(ws==ys) {
break;
} else if(ws<0||ws>ys) {
high=m-1;
} else {
low=m+1;
}
}
if(low>high)printf("Impossible");
else printf("%d",m);
return 0;
}
PAT Advanced 1010 Radix(25) [?分法]
原文:https://www.cnblogs.com/houzm/p/12247048.html