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
这道题目看起来很简单,其实有很多坑。
基数的下届容易确定,是这个数各位上最大数+1.
基数的上届是另一个数的值+1
用二分法求基数。
注意点:
1.只有一位数的基数可能有多个解。
2.最小的进制是2
3.用二分法求解时可能会超过long long的范围,变成负数
//#include "stdafx.h"
#include"stdio.h"
#include<iostream>
#include<string>
using namespace std;
typedef long long ll;
string s1,s2;
int tag;
ll r;
ll ans;//注意这里要用long long类型
ll cal(ll x){
ll ans2=0;
for(int i=0;i<s2.length();i++)
{ans2=ans2*x;
if(s2[i]>='0'&&s2[i]<='9')ans2+=s2[i]-'0';
else ans2+=s2[i]-'a'+10;
}
return ans2;
}
ll binarysearch(ll l,ll r){//l r mid都要用long long类型
while(l<=r){
ll mid=(l+r)/2;
ll ans1=cal(mid);
if(ans1==ans)return mid;
else if(ans1>ans||ans1<0)r=mid-1;//如果ans1<0是因为太大了
else l=mid+1;
}
return -1;
}
int main(){
// freopen("c://jin.txt","r",stdin);
while(cin>>s1>>s2>>tag>>r){
if(tag==2)swap(s1,s2);
ans=0;
for(int i=0;i<s1.length();i++)
{ans=ans*r;
if(s1[i]>='0'&&s1[i]<='9')ans+=s1[i]-'0';
else ans+=s1[i]-'a'+10;
}
while(s2.length()>1&&s2[0]=='0')s2.erase(s2.begin());//去掉前导0
if(s2.length()==1){//如果这个数是1位数,基数的解有无穷多个,取最小的一个
if(s2[0]=='0')if(ans==0)cout<<"2"<<endl;
else cout<<"Impossible"<<endl;
else{
int x;
if(s2[0]>='0'&&s2[0]<='9')x=s2[0]-'0';
else x=s2[0]-'a'+10;
if(x==ans)cout<<x+1<<endl;
else cout<<"Impossible"<<endl;
}}
else{
int ra=0;
for(int i=0;i<s2.length();i++)
{int x;
if(s2[i]>='0'&&s2[i]<='9')x=s2[i]-'0';
else x=s2[i]-'a'+10;
if(x>ra)ra=x;//ra是数位上的最大值
}
ra++;
ll x=binarysearch(ra,ans+1);
if(x==-1)cout<<"Impossible"<<endl;
else cout<<x<<endl;
}}
// freopen("CON","r",stdin);
// system("pause");
return 0;
}