Search code examples
javaalgorithmoptimizationbigdecimal

Is there a way to avoid BigInteger/BigDecimal?


I need to compute something like this (pseudocode):

// a, b, x, y are long, x,y <= 10^12

long i = (a - n)/(x*y)

and

long j = (b - n)/(x*y) - ceiling

Sometimes x*y doesn't fit in long. I would like to avoid BigDecimal/BigInteger usage as it is too costly and not needed anywhere else. Is there a smart math solution e.g. with two longs or smth like that?

Thank you!

UPDATE: Sorry, guys, one more constraint: I also have a variable computed as following (maybe it can be rewritten as well):

sum += x*y

I need to recalculate it to compare with another variable to stop the cycle.


Solution

  • I've noticed that the value I'm comparing the sum with is long. So I've solved the problem in the following way:

    • I'm calculating i like this: (long) (((a - n) / (double) x) / y))
    • Here goes j: (long) Math.ceil((b - n) / (double) x*y)
    • The case above overflows of course. But I prevent overflowing doing the following try-catch before:

              try {
                      xy = Math.multiplyExact(x, y);
                      ...
              } catch (ArithmeticException ex) {
                      // some handling
                      break;
              }
      

    This trick made by code work faster enough.

    Hope it helps someone!