由一个数的进制求另一个数的进制使这两个数在10进制的时候相等
注意:1.进制有可能会很大,因此两个数转化为10进制时都要使用longlong存储
2.因为进制的范围很广不止2-36,因此要用二分查找 范围是这个字符串里的最大字符+1到给出进制的数的十进制值+1,且要注意查找时转化为十进制数后还有可能溢出,要判断溢出时进制再往下取的情况
#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
int main()
{
string s1;
string s2;
int tag;
int radix;
cin>>s1>>s2>>tag>>radix;
long long sum=0,sum1=0;
int i;
long long j;
int flag=1;
if(s1=="0"&&s2=="0")
cout<<2<<endl;
else if(s1=="0"&&tag==2)
cout<<"Impossible"<<endl;
else if(s2=="0"&&tag==1)
cout<<"Impossible"<<endl;
else{
if(tag==1)
{
for(i=s1.size()-1;i>=0;i--)
if(isdigit(s1[i]))
sum+=pow(radix,s1.size()-1-i)*(s1[i]-'0');
else
sum+=pow(radix,s1.size()-1-i)*(s1[i]-'a'+10);
char max='0';
int r;
for(i=0;i<s2.size();i++)
{
if(s2[i]>max)
max=s2[i];
}
if(isdigit(max))
r=max-'0'+1;
else
r=max-'a'+10+1;
long long high=sum+1;
long long low =r;
for(j=(high+low)/2;low<=high;j=(high+low)/2)
{
sum1=0;
for(i=s2.size()-1;i>=0;i--)
if(isdigit(s2[i]))
sum1+=pow(j,s2.size()-1-i)*(s2[i]-'0');
else
sum1+=pow(j,s2.size()-1-i)*(s2[i]-'a'+10);
if(sum1>sum||sum1<0)
{
high=j-1;
}
else if(sum1<sum)
{
low=j+1;
}
else if(sum1==sum)
{
flag=0;
break;
}
}
if(flag==1)
printf("Impossible");
else
cout<<j;
}
if(tag==2)
{
for(i=s2.size()-1;i>=0;i--)
if(isdigit(s2[i]))
sum+=pow(radix,s2.size()-1-i)*(s2[i]-'0');
else
sum+=pow(radix,s2.size()-1-i)*(s2[i]-'a'+10);
char max='0';
int r;
for(i=0;i<s1.size();i++)
{
if(s1[i]>max)
max=s1[i];
}
if(isdigit(max))
r=max-'0'+1;
else
r=max-'a'+10+1;
long long high=sum+1;
long long low =r;
for(j=(high+low)/2;low<=high;j=(high+low)/2)
{
sum1=0;
for(i=s1.size()-1;i>=0;i--)
if(isdigit(s1[i]))
sum1+=pow(j,s1.size()-1-i)*(s1[i]-'0');
else
sum1+=pow(j,s1.size()-1-i)*(s1[i]-'a'+10);
if(sum1>sum||sum1<0)
{
high=j-1;
}
else if(sum1<sum)
{
low=j+1;
}
else if(sum1==sum)
{
flag=0;
break;
}
}
if(flag==1)
printf("Impossible");
else
cout<<j;
}
}
}
|