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 10
Sample Output 1:
2
Sample Input 2:
1 ab 1 2
Sample Output 2:
Impossible
#include<stdio.h> #include<string.h> #include<stdlib.h> long long binarySearch(); int cmp( long long k); char a[15],b[15],c[15]; long long ans[15]; long long low,high,len,valuea; int main() { int tag; long long radixa,temp,ret; int i; scanf("%s %s %d %lld",a,b,&tag,&radixa); if( tag==2) { strcpy(c,a); strcpy(a,b); strcpy(b,a); } for( i=0; a[i]!='\0'; i++) { if( a[i]>='0' && a[i]<='9') temp = a[i]-'0'; else if( a[i]>'a' && a[i]<'z') temp = a[i]-'a'+10; valuea = valuea*radixa + temp; } for( i=0; b[i]!='\0'; i++) { if( b[i]>='0' && b[i]<='9') temp = b[i]-'0'; else if( b[i]>'a' && b[i]<'z') temp = b[i]-'a'+10; ans[i]=temp; if( low<temp) low = temp; } low++; len = strlen(b); if( low>valuea) high = low+1; else high=valuea+1; ret = binarySearch(); if( ret==-1) printf("Impossible\n"); else printf("%lld\n",ret); return 0; } long long binarySearch() { long long l=low,h=high,mid; while( l<=h ) { mid = (l+h)/2; if(cmp(mid)==0) return mid; else if(cmp(mid)<0) l= mid+1; else h=mid-1; } return -1; } int cmp( long long k) { long long valueb=0; int i; for( i=0; i<len; i++) valueb = k*valueb+ans[i]; if( valueb<0 || valueb>valuea) return 1; else if( valueb<valuea) return -1; else if ( valuea==valueb) return 0; }