0

Coding puzzles generally ask to give result mod (10^9+7). Refer the explanations here.

Suppose I have a 2 very big number; say 2 large string of numeric characters. I need to add them and result processed as mod (10^9+7). How can i achieve that.

e.g. if they were small numbers code will look like

    Integer a = Integer.parseInt("123");
    Integer b = Integer.parseInt("456");
    Integer result = (a+b)%(10^9+7);
    System.out.println("result"+result);

How to do same with very big numbers ?

    Integer a = Integer.parseInt("123456474575756568568786786786786783453453");
    Integer b = Integer.parseInt("456534543654564567567567567567564564456");
    Integer result = (a+b)%(10^9+7);
    System.out.println("result"+result);

In this case something other than Integer needs to be used and "add","modulo" operation should be performed.

I could not easily use BidInteger, BigDecimal in this case. Please suggest.

Kaushik Lele
  • 6,439
  • 13
  • 50
  • 76
  • 2
    "could not easily use BidInteger" - what's the problem? Should just work. FWIW you can also parse the numbers manually and apply the modulo reduction as you go, then the numbers never get big in the first place. – harold Mar 06 '17 at 14:07
  • 6
    `10^9+7` is **not** how you write 10 to the power 9 plus 7 in Java. The `^` is the XOR operator, not the power operator. – Jesper Mar 06 '17 at 14:09
  • If the numbers you want to work with are even nearly as big as showed in the example, then `double` and `BigInteger` are the only way to do so. `Integer` is not enough – Anand Undavia Mar 06 '17 at 14:09
  • 1
    Seems to work with BigInteger: [ideone](http://ideone.com/wp0UzH) – harold Mar 06 '17 at 14:13

1 Answers1

4

BigInteger is not so bad, and it does exactly what you need:

BigInteger a = new BigInteger("123456474575756568568786786786786783453453");
BigInteger b = new BigInteger("456534543654564567567567567567564564456");
BigInteger result = a.add(b).mod(BigInteger.TEN.pow(9).add(BigInteger.valueOf(7)));
System.out.println("result: " + result);

Output:

result: 560775910

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588