题意 给你两个二进制数m,n 求他们的最大公约数 用二进制表示 0<m,n<2^1000
先把二进制转换为十进制 求出最大公约数 再把结果转换为二进制 数比較大要用到大数
import java.util.*;
import java.math.*;
public class wl6_9 {
static BigInteger two = BigInteger.valueOf(2), one = BigInteger.ONE,
zero = BigInteger.ZERO;
static BigInteger gcd(BigInteger a, BigInteger b) {
while (!(a.mod(b).equals(zero))) {
BigInteger t = a.mod(b);
a = b;
b = t;
}
return b;
}
static void bprint(BigInteger x) {
if (x.equals(zero))
return;
bprint(x.divide(two));
if (x.mod(two).equals(one))
System.out.print(1);
else
System.out.print(0);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
String a, b;
for (int t = 1; t <= T; t++) {
a = in.next();
b = in.next();
int la = a.length(), lb = b.length();
BigInteger m = zero, n = zero;
for (int i = 0; i < la; ++i) {
m = m.multiply(two);
if (a.charAt(i) == '1')
m = m.add(one);
}
for (int i = 0; i < lb; ++i) {
n = n.multiply(two);
if (b.charAt(i) == '1')
n = n.add(one);
}
System.out.printf("Case #%d: ", t);
bprint(gcd(m, n));
System.out.println();
}
in.close();
}
}
3 10 100 100 110 10010 1100
Case #1: 10 Case #2: 10 Case #3: 110
原文:http://www.cnblogs.com/mengfanrong/p/4019222.html