PKU1331代码题意: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.给三个数 p,q,r 从2到16中找出一个进制,使得r为p与q的乘积.题目隐含要求:1、进制不能小于p,q,r里边包含的最大数字. 2、输入为10进制。解题过程: 给定一个base,先将pqr转换成10进制数,然后进行计算。 #include <iostream>#include <cstdlib>#include <stack>using namespace std;int basecalc(int p,int q,int r,int base){ stack <int> s; int pinten=0,qinten=0,rinten=0; while(p) { s.push(p%10); p/=10; } while(!s.empty()) { pinten=pinten*base+s.top(); s.pop(); } while(q) { s.push(q%10); q/=10; } while(!s.empty()) { qinten=qinten*base+s.top(); s.pop(); } while(r) { s.push(r%10); r/=10; } while(!s.empty()) { rinten=rinten*base+s.top(); s.pop(); } if(pinten*qinten==rinten) return base; else return 17;}int main(){ int t; int p,q,r; cin>>t; for(int i=0;i<t;i++) { int base=0; int max=0; int min=17; cin>>p>>q>>r; int pp=p,qq=q,rr=r; while(pp) { if(max<pp%10) max=pp%10; pp/=10; } while(qq) { if(max<qq%10) max=qq%10; qq/=10; } while(rr) { if(max<rr%10) max=rr%10; rr/=10; } for(base=max+1;base<=16;base++) { int mm=basecalc(p,q,r,base); if(min>mm) min=mm; } if(min==17) cout<<0<<endl; else cout<<min<<endl; } return EXIT_SUCCESS;}

评论