PAT 1010. Radix (25)

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
 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 
 7 long long ToRadix(string num, long long radix)
 8 {
 9     long long res = 0;
10     for (int i = 0; i < num.size(); i++)
11     {
12         int x = (num[i] >= '0'&&num[i] <= '9') ? num[i] - '0' : num[i] - 'a' + 10;
13         res = res*radix + x;
14     }
15 
16     return res;
17 }
18 
19 int main()
20 {
21     string num[2];
22     int tag;
23     long long radix;
24 
25     cin >> num[0] >> num[1] >> tag >> radix;
26     long long base = ToRadix(num[tag - 1], radix);
27 
28     string number = num[2 - tag];
29     if (number.size() == 1)
30     {
31         int x = (number[0] >= '0'&&number[0] <= '9') ? number[0] - '0' : number[0] - 'a' + 10;
32         if (x == base)
33             cout << x + 1;
34         else
35             cout << "Impossible";
36 
37         return 0;
38     }
39 
40     long long minRadix = 0, maxRadix = base;
41     for (int i = 0; i < number.size(); i++)
42     {
43         int x = (number[i] >= '0'&&number[i] <= '9') ? number[i] - '0' : number[i] - 'a' + 10;
44         if (x + 1 > minRadix)
45             minRadix = x + 1;
46     }
47 
48     while (minRadix <= maxRadix)
49     {
50         long long middle = (minRadix + maxRadix) / 2;
51         long long x = ToRadix(number, middle);
52         if (x == base)
53         {
54             cout << middle;
55             return 0;
56         }
57         else if (x > base || x<0)
58             maxRadix = middle - 1;
59         else
60             minRadix = middle + 1;
61     }
62 
63     cout << "Impossible";
64 }

 



posted @ 2015-08-20 20:43  JackWang822  阅读(183)  评论(0编辑  收藏  举报