So I am doing this problem which requires to calculate the equations. At first i thought long
would be enough for the range but now it has exceeded the long
range and now i have to use BigInteger
. I have to convert one equation but I haven't been able to
This is the equation :
count =(n2/n3)-((n1-1)/n3);
Count can be long
but n1
, n2
, n3
should be BigInteger
.
This simplifies to:
-(n1-n2-1)/n3
and in Java
BigInteger count = n1
.subtract(n2)
.subtract(BigInteger.valueOf(1))
.negate()
.divide(n3)
BigInteger seems to have a longValue() method that should be able to do the job: 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()
This oneliner should do the trick...
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();
You can use 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())));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.