-3

I am working with large numbers in Java. I don't know if I should parse String to BigInteger once, and calculate mod of that number, or if I should better divide that String into segments and parse those segments to int and calculate mod like that.

I am striving for best performance. Which is the better way?

Don Branson
  • 13,631
  • 10
  • 59
  • 101
Kima
  • 3
  • 1
  • 6
    Why not try both options and then benchmark? It will be a great learning experience. – sstan Jul 12 '16 at 17:38
  • 3
    If you do decide to benchmark it, make sure to avoid the [common mistakes people make](http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java). – resueman Jul 12 '16 at 17:39
  • BigInteger is implemented with an `int[]`. The mod operation has two different algorithms, chosen based on various conditions, to achieve good performance. It's unlikely that you can do much better (unless you use case is very specific and you can take some shortcuts that are not possible in a general purpose class)... – assylias Jul 12 '16 at 17:49
  • We almost need a special close category for these performance questions. Just measure it. – Don Branson Jul 12 '16 at 20:14
  • why was this downvoted? it doesn't seem to me to be that embarrassing to ask. – Balázs Németh Jul 12 '16 at 20:16

1 Answers1

0

BigInteger is made to do such things, and current implementations are pretty well optimized.

Also, I wonder how you want to partition the string so that you actually get the correct mod result using longs or ints, without having to take care of a number of corner cases and without intensive testing.

So while I agree that, if you really want to implement your own algorithm, you should actually profile this and compare the performance to BigInteger, I personally don't think that trying to reinvent the wheel is necessary. I would use BigInteger.

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94