好像有几天没有写了,之前其实耶做了一题不过忘了写题解了,记得填坑记得好象是1026 置换群什么的。
今天写的是1331单单纯纯地数位转换,其实没什么特别注意的,不过在进行等比进制转换的时候采用秦九韶算法可以明显优化速度,诶嘿!
POJ 1331 Multiply
Description
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.
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.
Input
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.
Output
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.
Sample Input
3 6 9 42 11 11 121 2 2 2
Sample Output
13 3 0
代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
long multiply(char* num,int base){
long ret=0;
int i;
for(i=0;i<strlen(num);i++){
if(num[i]-'0'>=base) return -1;
ret*=base;
ret+=num[i]-'0';
}
return ret;
}
int main(){
int t;
char r[10],q[10],p[10];
scanf("%d",&t);
while(t--){
scanf("%s%s%s",p,q,r);
int b;
for(b=2;b<=16;b++){
long pp,qq,rr;
pp=multiply(p,b);
qq=multiply(q,b);
rr=multiply(r,b);
if(pp==-1||qq==-1||rr==-1) continue;
else if(pp*qq==rr){
printf("%d\n",b);
break;
}
}
if(b==17) printf("0\n");
}
return 0;
}
又可以多刷一道水题了!