如何将等式从 long 转换为 Biginteger
How to convert equation from long to Biginteger
所以我正在做这个需要计算方程的问题。起初我认为 long
就足够了,但现在它已经超出了 long
的范围,现在我必须使用 BigInteger
。我必须转换一个方程式,但我无法做到
这是等式:
count =(n2/n3)-((n1-1)/n3);
计数可以是 long
但 n1
、n2
、n3
应该是 BigInteger
.
BigInteger 似乎有一个 longValue() 方法应该能够完成这项工作:
http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html
long count = (n2
.divide(n3))
.substract( (n1
.subtract(BigInteger.ONE))
.divide(n3)
).longValue()
您可以使用BigInteger#valueOf(long val)
count = (BigInteger.valueOf(n2.intValue()).divide(BigInteger.valueOf(n3.intValue()))).
subtract(((BigInteger.valueOf(n1.intValue()).
subtract(BigInteger.valueOf(n1.intValue()))).
divide(BigInteger.valueOf(n3.intValue())));
这个 oneliner 应该可以解决问题...
long count;
BigInteger n1, n2, n3;
n1 = n2 = n3 = new BigInteger("1231232");
//count =(n2/n3)-((n1-1)/n3);
//count = (n2/n3)
count = (n2.divide(n3))
// -
.subtract(
//((n1-1)/n3);
((n1.subtract(new BigInteger("1").divide(n3))))
).longValue();
这简化为:
-(n1-n2-1)/n3
并在 Java
BigInteger count = n1
.subtract(n2)
.subtract(BigInteger.valueOf(1))
.negate()
.divide(n3)
所以我正在做这个需要计算方程的问题。起初我认为 long
就足够了,但现在它已经超出了 long
的范围,现在我必须使用 BigInteger
。我必须转换一个方程式,但我无法做到
这是等式:
count =(n2/n3)-((n1-1)/n3);
计数可以是 long
但 n1
、n2
、n3
应该是 BigInteger
.
BigInteger 似乎有一个 longValue() 方法应该能够完成这项工作: http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html
long count = (n2
.divide(n3))
.substract( (n1
.subtract(BigInteger.ONE))
.divide(n3)
).longValue()
您可以使用BigInteger#valueOf(long val)
count = (BigInteger.valueOf(n2.intValue()).divide(BigInteger.valueOf(n3.intValue()))).
subtract(((BigInteger.valueOf(n1.intValue()).
subtract(BigInteger.valueOf(n1.intValue()))).
divide(BigInteger.valueOf(n3.intValue())));
这个 oneliner 应该可以解决问题...
long count;
BigInteger n1, n2, n3;
n1 = n2 = n3 = new BigInteger("1231232");
//count =(n2/n3)-((n1-1)/n3);
//count = (n2/n3)
count = (n2.divide(n3))
// -
.subtract(
//((n1-1)/n3);
((n1.subtract(new BigInteger("1").divide(n3))))
).longValue();
这简化为:
-(n1-n2-1)/n3
并在 Java
BigInteger count = n1
.subtract(n2)
.subtract(BigInteger.valueOf(1))
.negate()
.divide(n3)