给出三个整数a,b,c,请找出最小的进制K(2<=K<=16)使得a*b=c在K进制下成立。
比如a=11,b=10,c=110。那么当K=2的时候 (11)2 ∗ (10)2 = (110)2 成立,当K=10的时候 (11)10 ∗ (10)10 = (110)10 也成立。
输入
单组测试数据。
输入三个整数a,b,c(1<=a,b,c<=1,000,000),a,b,c的每位数字都是0到9的。
输出
输出一个整数表示答案,如果[2,16]这个区间内没有符合要求的进制,输出0。
输入样例
样例输入1
11 10 110
输出样例
样例输出1
2
题解:
枚举法,让进制k从max_v+1(后面解释max_v是什么意思)枚举到16即可,每次都将k进制转换成十进制看是否满足ak * bk = ck,上面有个max_v+1,就是本题需要注意的一点,比如a,b,c中出现的最大数字是2,那么进制最小都只能是3进制。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;
int a,b,c;
// 找出a,b,c三个数中所有位数中最大的数(进制数肯定比max_value大,至少要是max_value+1)
int getMaxValue(int a,int b,int c)
{
int max_value = 0;
while(a)
{
if(a%10 > max_value)
max_value = a%10;
a /= 10;
}
while(b)
{
if(b%10 > max_value)
max_value = b%10;
b /= 10;
}
while(c)
{
if(c%10 > max_value)
max_value = c%10;
c /= 10;
}
return max_value;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
while(cin >> a >> b >> c)
{
int max_v = getMaxValue(a,b,c);
int k;
for(k = max_v+1; k <= 16; k++)
{
int a_10,b_10,c_10;// 将a、b、c从k进制转换十进制
a_10 = b_10 = c_10 = 0;
int t_a = a;
int t_b = b;
int t_c = c;
int r = 0;
while(t_a)
{
a_10 += (t_a%10)*(int)pow(k,r++);
t_a /= 10;
}
r = 0;
while(t_b)
{
b_10 += (t_b%10)*(int)pow(k,r++);
t_b /= 10;
}
r = 0;
while(t_c)
{
c_10 += (t_c%10)*(int)pow(k,r++);
t_c /= 10;
}
//printf("a_10 = %d b_10 = %d c_10 = %d\n",a_10,b_10,c_10);
if(a_10 * b_10 == c_10)
{
cout << k << endl;
break;
}
}
if(k == 17)
{
cout << 0 << endl;
}
}
return 0;
}