Multiply

来源:互联网 发布:u盘坏了找回数据多少钱 编辑:程序博客网 时间:2024/05/18 01:27

Multiply

总时间限制: 1000ms 内存限制: 65536kB
描述
6*9 = 42” is not true for base 10, but is true for base 13. That is, 6(13) * 9(13) = 42(13) because 42(13) = 4 * 131 + 2 * 130 = 54(10).

You are to write a program which inputs three integers p, q, and r and determines the base B (2<=B<=16) for which p * q = r. If there are many candidates for B, output the smallest one. For example, let p = 11, q = 11, and r = 121. Then we have 11(3) * 11(3) = 121(3) because 11(3) = 1 * 31 + 1 * 30 = 4(10) and 121(3) = 1 * 32 + 2 * 31 + 1 * 30 = 16(10). For another base such as 10, we also have 11(10) * 11(10) = 121(10). In this case, your program should output 3 which is the smallest base. If there is no candidate for B, output 0.
输入
The input consists of T test cases. The number of test cases (T ) is given in the first line of the input file. Each test case consists of three integers p, q, and r in a line. All digits of p, q, and r are numeric digits and 1<=p,q, r<=1,000,000.
输出
Print exactly one line for each test case. The line should contain one integer which is the smallest base for which p * q = r. If there is no such base, your program should output 0.
样例输入
3
6 9 42
11 11 121
2 2 2
样例输出
13
3
0

#include <iostream>#include<string.h>using namespace std;//http://bailian.openjudge.cn/exam/3658/3///b进制转10进制,一般都是用char数组存储的 int n,flag;char p[8],q[8],r[8];int pp,qq,rr;int b2t(char x[],int b){    int res=0,len=strlen(x);    for(int i=0;i<len;i++){        if(x[i]-'0'>=b){            return -1;        }        else{            res=res*b+(x[i]-'0');        }    }    return res;}int main(int argc, char *argv[]) {    cin>>n;    while(n--){        flag=0;        cin>>p>>q>>r;        for(int i=2;i<=16;i++){            pp=b2t(p,i);            if(pp!=-1){                qq=b2t(q,i);                if(qq!=-1){                    rr=b2t(r,i);                    if(rr!=-1&&rr==pp*qq){                        cout<<i<<endl;                        flag=1;                        break;                    }                }            }        }        if(flag==0){            cout<<"0"<<endl;        }    }    return 0;}
原创粉丝点击