How to convert equation from long to Biginteger

1k Views Asked by At

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.

4

There are 4 best solutions below

5
On BEST ANSWER

This simplifies to:

-(n1-n2-1)/n3

and in Java

BigInteger count = n1
  .subtract(n2)
  .subtract(BigInteger.valueOf(1))
  .negate()
  .divide(n3)
0
On

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()
1
On

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())));
1
On

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();