4

I'm trying to solve some problems on interviewstreet. For some problems they mention As the answers can be very big, output them modulo 1000000007. How can I compute a*b mod N where N is a large number like 1000000007.

I thought of using

(a mod N) * (b mod N) = (a*b mod N)

but I reckon performing this wouldn't work. Example :

a=4, b=5 and N=10
(4 mod 10) * (5 mod 10) = 20
whereas (4*5 mod 10) = 2

Can somebody guide me in the right direction.

nikhil
  • 143
  • 1
  • 1
  • 5

1 Answers1

4

You can do the mod any time you like, before multiplication or after.

For another thing $4*5\equiv 0\pmod{10}$, not 2.

For example $16*12\equiv 192\equiv 2\pmod{10}$ and also

$16*12\equiv (10+6)*(10+2)\equiv 6*2\equiv 12\equiv 2\pmod{10}$

It's always advisable to mod before you multiply, as it will keep the numbers as small as possible.

rschwieb
  • 153,510
  • But note that, as in the example, you may have to mod again after you multiply, because the product of two numbers less than N can still be greater than N. You can't really avoid the divide - and in the case of multiplying mod 1000000007 , this means that your intermediate won't necessarily fit in 32 bits so you may need to use 64-bit integers for intermediate results. – Steven Stadnicki Jun 01 '12 at 21:01
  • To add onto StevenStadnicki's observation: From the mathematician's point of view, there's no problem with $12\pmod{10}$, it's just that $12$ and $2$ are identical, so you can interchange them. I suppose for computer science there would be a strong impetus to reduce in order to save memory. – rschwieb Jun 01 '12 at 21:08