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这题不难,主要是要考虑数据溢出的问题,和使用二分法去寻找匹配的二进制,而二分法中的左右边界是要考虑怎么得到的,这是个难点
1 #include <iostream> 2 #include <string> 3 #include<math.h> 4 #include <cctype> 5 #include <algorithm> 6 using namespace std; 7 8 //最简单的一种一种格式试 9 int main() 10 { 11 string N1, N2; 12 long long int tag,radix;//防止溢出 13 cin >> N1 >> N2 >> tag >> radix; 14 if (tag == 2) 15 { 16 string N = N2; 17 N2 = N1; 18 N1 = N; 19 } 20 long long int aim = 0, n = 0;//防止化为10制止时溢出 21 for (int i = N1.length() - 1, j = 0; i >= 0; ++j, --i)//将N1划为10进制 22 { 23 n = isdigit(N1[i]) ? (N1[i] - '0') : (N1[i] - 'a' + 10); 24 aim += n * pow(radix, j); 25 } 26 long long int l, r, m; 27 char it = *max_element(N2.begin(), N2.end());//找出最大的元素 28 l = (isdigit(it) ? it - '0' : it - 'a' + 10) + 1;//找到N2形成的最小进制 29 r = max(aim, l); 30 while (l <= r) 31 { 32 m = l + (r - l) / 2; 33 long long int res = 0, n; 34 for (int i = N2.length() - 1, j = 0; i >= 0; ++j, --i) 35 { 36 n = isdigit(N2[i]) ? (N2[i] - '0') : (N2[i] - 'a' + 10); 37 res += n * pow(m, j); 38 } 39 if (res == aim) 40 break; 41 else if (res<0 || res>aim) 42 r = m - 1; 43 else 44 l = m + 1; 45 } 46 if (l > r) 47 cout << "Impossible" << endl; 48 else 49 cout << m << endl; 50 51 return 0; 52 53 }
来源:https://www.cnblogs.com/zzw1024/p/11178506.html