1010. Radix (25)
Given a pair of positive integers, for example, 6 and 110, can this equation 6 = 110 be true? The answer is "yes", if 6 is a decimal number and 110 is a binary number.
Now for any pair of positive integers N1 and N2, your task is to find the radix of one number while that of the other is given.
Input Specification:
Each input file contains one test case. Each case occupies a line which contains 4 positive integers:
N1 N2 tag radix
Here N1 and N2 each has no more than 10 digits. A digit is less than its radix and is chosen from the set {0-9, a-z} where 0-9 represent the decimal numbers 0-9, and a-z represent the decimal numbers 10-35. The last number "radix" is the radix of N1 if "tag" is 1, or of N2 if "tag" is 2.
Output Specification:
For each test case, print in one line the radix of the other number so that the equation N1 = N2 is true. If the equation is impossible, print "Impossible". If the solution is not unique, output the smallest possible radix.
Sample Input 1:6 110 1 10Sample Output 1:
2Sample Input 2:
1 ab 1 2Sample Output 2:
Impossible
推荐指数:※※※
来源:http://pat.zju.edu.cn/contests/pat-a-practise/1010
这道题目的大体意思是有两个数,其中一个数的进制已经知道,假设两个数相等,求出另一个数的进制,若果有就输出 求出的进制,如果没有就输出 Impossible.
进制转换是常见的代码,首先想到了是从1开始的每个数都试一遍。
再想想,这其实就是找一个合适的进制,使得某个输入等于特定的数。特定进制可能可能会时这个数大于特定的数,也可能小于特定的数。这一有点像二分法。实际上,确实用的是二分法。
下面附上一段代码:
#include<iostream> #include<math.h> #define N 11 using namespace std; int chartoint(char ch){//把char转换成数字 if(ch>='0'&&ch<='9'){ return ch-'0'; } else if(ch>='a'&&ch<='z'){ return ch-'a'+10; } return -1; } int find_radix(int n1[],int n2[],int radix1,int len)//n1:已经知进制的数,n2:未知进制的数,len:n2数的长度 { long p,q; long k, i, max_k, min_k; p=0; i=0; while(n1[i]!=-1){//求出n1表示的数 p=n1[i++]+p*radix1; } if(len==1){ if(n2[0]==p) return n2[0]+1; else return -1; } else{ max_k=pow(p,1.0/(len-1));//进制上限 min_k=pow(p,1.0/len);//进制下限 k=0; do{//二分法查找 k=(min_k+max_k)/2; q=0;i=0; while(n2[i]!=-1){ q=n2[i]+q*k; i++; } if(q>p) max_k=k-1; else if(q<p) min_k=k+1; else return k; }while(min_k<=max_k); } return -1; } int main(void) { int n1[N],n2[N]; int tag,radix_know,radix_find; int i,j; int count=0; int len_n1=0,len_n2=0; char ch; for(i=0;i<N;i++){ n1[i]=0; n2[i]=0; } ch=getchar(); i=0; while(ch!=' '){ n1[i++]=chartoint(ch); ch=getchar(); len_n1++; } n1[i]=-1; ch=getchar(); i=0; while(ch!=' '){ n2[i++]=chartoint(ch); ch=getchar(); len_n2++; } n2[i]=-1; cin>>tag; cin>>radix_know; if(tag==1) radix_find=find_radix(n1,n2,radix_know,len_n2); else radix_find=find_radix(n2,n1,radix_know,len_n1); if(radix_find==-1) cout<<"Impossible"<<endl; else cout<<radix_find<<endl; return 0; }

探讨了在已知其中一个数的进制情况下,如何通过算法找到另一个数的进制,使得两数相等的问题。文章详细介绍了使用二分法进行搜索的方法,包括将字符转换为数字、进制转换算法实现及复杂度分析。
1526

被折叠的 条评论
为什么被折叠?



