Kaushik Lele
Kaushik Lele

Reputation: 6637

How to do mod (10^9+7) for large numbers in Java

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.

Upvotes: 0

Views: 5732

Answers (1)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299148

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

Upvotes: 4

Related Questions