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
题意:给出一个数和它的基数,以及另外一个数,求这两个数相等时,另一个数的根
思路:由于radix的范围不确定,简单遍历tle,需要用二分搜索。
#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std;
typedef long ll;
ll change(char c)
{
if(isdigit(c)) return c-'0';
return c-'a'+10;
}
ll D_Ten(string s,ll D)//D进制转为10进制
{
ll ans=0;
int len=s.length();
for(int i=0;i<len;i++)
{
ans=ans*D+change(s[i]);
}
return ans;
}
ll Maxnum(string s)
{
ll d=-1;
for(int i=0;i<s.size();i++)
{
ll num;
num=change(s[i]);
if(num>d) d=num;
}
return d+1;
}
int cmp(string s,ll D,ll num1)
{
ll ans=0;
ll d=1;
for(int i=s.size()-1;i>=0;i--)
{
int num=change(s[i]);
ans=ans+num*d;
if(ans>num1) return 1;
d*=D;
}
if(ans==num1) return 0;
return -1;
}
int main()
{
int c;ll d;
string s1,s2;
cin>>s1>>s2>>c>>d;
if(s1=="1"&&s2=="1")
cout<<2<<endl;
else if(s1==s2)
{
cout<<d<<endl;
}
else
{
if(c==2)
{
string s3=s1;
s1=s2;
s2=s3;
}
bool flag=false;
ll res1=D_Ten(s1,d);
ll l=Maxnum(s2);
ll r=max(l,res1),m;
while(r>=l)
{
m=(l+r)/2;
int res=cmp(s2,m,res1);
if(res==0)
{
flag=true;
break;
}
else
{
if(res==1) r=m-1;
else l=m+1;
}
}
if(flag&&D_Ten(s2,m)==res1) cout<<m<<endl;
else cout<<"Impossible"<<endl;
}
return 0;
}