问题描述
6*9 = 42 对于十进制来说是错误的,但是对于13 进制来说是正确的。即, 6(13) * 9(13) = 42(13), 而 42(13) = 4 * 131 + 2 * 130 = 54(10)。 你的任务是写一段程序读入三个整数p、q 和 r,然后确定一个进制 B(2<=B<=16) 使得 p * q = r. 如果 B 有很多选择, 输出最小的一个。例如: p = 11, q = 11, r = 121. 则有 11(3) * 11(3) = 121(3) 因为 11(3) = 1 * 31 + 1 * 30 = 4(10) 和 121(3) = 1 * 32 + 2 * 31 + 1 * 30 = 16(10)。 对于进制 10,有 11(10) * 11(10) = 121(10)。这种情况下,应该输出 3。如果没有合适的进制,则输出 0。
输入数据
输入有 T 组测试样例。 T 在第一行给出。每一组测试样例占一行,包含三个整数p、q、r。 p、q、r 的所有位都是数字,并且1 <= p、q、r <= 1,000,000。
输出要求
对于每个测试样例输出一行。该行包含一个整数:即使得p * q = r 成立的最小的B。如果没有合适的B,则输出 0。
输入样例
3
6 9 42
11 11 121
2 2 2
输出样例
13
3
0
参考程序
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Radix
1
#include <iostream>
2
using namespace std;
3![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
4
long b2ten(char* x, int b)
5![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
6
int ret = 0;
7
int len = strlen(x);
8
for(int i = 0; i < len; i++)
9![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
10
if(x[i]-'0' >= b)
11![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
12
return -1;
13
}
14
ret *= b;
15
ret += x[i]-'0';
16
}
17![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
18
return (long)ret;
19
}
20![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
21
void main()
22![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
23
int n;
24
char p[8], q[8], r[8];
25
long pAlgorism, qAlgorism, rAlgorism;
26
cin >> n;
27
while(n--)
28![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
29
cin >> p >> q >> r;
30
for(int b=2; b <= 16; b++)
31![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
32
pAlgorism = b2ten(p, b);
33
qAlgorism = b2ten(q, b);
34
rAlgorism = b2ten(r, b);
35
if(pAlgorism == -1 ||
36
qAlgorism == -1 ||
37
rAlgorism == -1)
38![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
39
continue;
40
}
41![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
42
if(pAlgorism * qAlgorism == rAlgorism)
43![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
44
cout << b << endl;
45
break;
46
}
47
}
48![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
49
if(b == 17)
50![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
51
cout << "0" << endl;
52
}
53
}
54
}