[英]java biginteger not working
输入文本 5 1 5 7 10 123456789123456789
因为输入值大所以使用binginteger
不适用于 123456789123456789。我不知道哪个是错误的。
对于博弈方法,两个人首先决定一个正整数 N 并有一个初始化为 1 的 x。
爱丽丝首先开始游戏,然后轮流自己做以下工作。
用 2x 或 2x + 1 替换 x。
当 x 大于 N(超过)时,完成工作的人就失败了。
我的代码如下。
public static Boolean result(int X, BigInteger N) {
if(X == 0)
return false;
else if(X % 2 == 0) {
BigInteger check = BigInteger.valueOf((int)((3*Math.pow(2,X)-1)/2));
if(check.compareTo(N) == 1 || check.compareTo(N) == 0)
return true;
else
return false;
}
else
return true;
}
public static int returnX(BigInteger N) {
int X = 0;
while(true) {
if((BigInteger.valueOf((int)Math.pow(2,X)).compareTo(N) == -1
|| BigInteger.valueOf((int)Math.pow(2,X)).compareTo(N) == 0)
&& N.compareTo(BigInteger.valueOf((int)Math.pow(2,X+1))) == -1)
break;
X++;
}
return X;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int T;
T = sc.nextInt();
BigInteger[] N = new BigInteger[T];
for (int test_case = 1; test_case <= T; test_case++) {
N[test_case-1] = sc.nextBigInteger();
}
for (int test_case = 1; test_case <= T; test_case++) {
if(result(returnX(N[test_case-1]),N[test_case-1])) {
System.out.printf("#%d Alice\n",test_case);
}
else
System.out.printf("#%d Bob\n",test_case);
}
}
您必须在BigInteger
进行所有数学运算。 例如,
BigInteger.valueOf((int)((3*Math.pow(2,X)-1)/2))
应该是
BigInteger.valueOf(3)
.multiply(BigInteger.valueOf(2).pow(x))
.subtract(BigInteger.ONE)
.divide(BigInteger.valueOf(2))
...等等,直到你的程序的其余部分。 如果您在调用BigInteger.valueOf
进行任何数学运算,则可能是错误的。
在函数返回 X 中,你写了
if((BigInteger.valueOf((int)Math.pow(2,X)).compareTo(N) == -1
|| BigInteger.valueOf((int)Math.pow(2,X)).compareTo(N) == 0)
&& N.compareTo(BigInteger.valueOf((int)Math.pow(2,X+1))) == -1)
它将永远小于 N
所以试试这个:
if((BigInteger.valueOf(2).pow(X).compareTo(N) == -1
|| BigInteger.valueOf(2).pow(X).compareTo(N) == 0)
&& N.compareTo(BigInteger.valueOf(2).pow(X+1)) == -1)
它会工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.