PAT甲级——A1010 Radix

时间:2023-03-09 15:06:17
PAT甲级——A1010 Radix

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 <iostream>
#include <string>
#include<math.h>
#include <cctype>
#include <algorithm>
using namespace std; //最简单的一种一种格式试
int main()
{
string N1, N2;
long long int tag,radix;//防止溢出
cin >> N1 >> N2 >> tag >> radix;
if (tag == )
{
string N = N2;
N2 = N1;
N1 = N;
}
long long int aim = , n = ;//防止化为10制止时溢出
for (int i = N1.length() - , j = ; i >= ; ++j, --i)//将N1划为10进制
{
n = isdigit(N1[i]) ? (N1[i] - '') : (N1[i] - 'a' + );
aim += n * pow(radix, j);
}
long long int l, r, m;
char it = *max_element(N2.begin(), N2.end());//找出最大的元素
l = (isdigit(it) ? it - '' : it - 'a' + ) + ;//找到N2形成的最小进制
r = max(aim, l);
while (l <= r)
{
m = l + (r - l) / ;
long long int res = , n;
for (int i = N2.length() - , j = ; i >= ; ++j, --i)
{
n = isdigit(N2[i]) ? (N2[i] - '') : (N2[i] - 'a' + );
res += n * pow(m, j);
}
if (res == aim)
break;
else if (res< || res>aim)
r = m - ;
else
l = m + ;
}
if (l > r)
cout << "Impossible" << endl;
else
cout << m << endl; return ; }