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
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
有幾個樣例挺簡單的,除了 第 7個,他的可能正確的數值高達 1e8。 暴力是不可能暴力的,只能二分這個樣子。
所以java 寫一下就好了。
import java.math.*;
import java.util.*;
public class Main {
public static int get_dig(char ch) {
int res;
if(ch>='0'&&ch<='9')res=ch-'0';
else res=ch-'a'+10;
return res;
}
public static int check(BigInteger x,BigInteger sum,String s) {
BigInteger res=BigInteger.ZERO;
for(int i=0;i<s.length();i++) {
BigInteger tmp=BigInteger.valueOf(get_dig(s.charAt(i)));
res=res.multiply(x).add(tmp);
}
if(res.equals(sum))return 0;
if(res.compareTo(sum)>0)return 1;
return -1;
}
public static void main(String []args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()) {
String str[]=new String[2];
int len[]=new int[2];
str[0]=sc.next();str[1]=sc.next();
int tag,dig;
tag=sc.nextInt();dig=sc.nextInt();
tag--;
int t2=1-tag;
BigInteger sum=BigInteger.valueOf(0),Dig=BigInteger.valueOf(dig);
len[tag]=str[tag].length();len[t2]=str[t2].length();
int flag=0;
for(int i=0;i<len[tag];i++) {
BigInteger tmp=BigInteger.valueOf(get_dig(str[tag].charAt(i)));
sum=sum.multiply(Dig).add(tmp);
if(tmp.compareTo(Dig)>=0) {
flag=1;
}
}
if(flag==1) {
System.out.printf("Impossible\n");
continue;
}
int M=0;
for(int i=0;i<len[t2];i++) {
int tmp=get_dig(str[t2].charAt(i));
if(M<tmp)M=tmp;
//M=max(M,get_dig(str[t2].charAt(i)));
}
BigInteger ans=new BigInteger("0");
BigInteger l=BigInteger.valueOf(M+1),r=new BigInteger("10000000000"),mid;
while(l.compareTo(r)<=0) {
mid=(l.add(r)).shiftRight(1);
int f=check(mid,sum,str[t2]);
if(f>=0) {
if(f==0)ans=mid;
r=mid.subtract(BigInteger.ONE);
}else {
l=mid.add(BigInteger.ONE);
}
}
if(ans.equals(BigInteger.ZERO)) {
System.out.printf("Impossible\n");
}else {
System.out.println(ans);
}
}
sc.close();
}
}