2

Possible Duplicate:
Need help in mod 1000000007 questions

I have a set of numbers for which i want to compute total product modulo 1000007. e.g if my array contains 1000 numbers then i need to compute the following.

int product = 1;
for(int i=0;i<Array_Max;i++)
  product = product * Array[i]

then product modulo 1000007 = ?

Is there any algorithm to optimize the above pseudo code ? Right now i am unable to store the product because of overflow.

Any suggestion appreciated.

Community
  • 1
  • 1
Alok
  • 229
  • 1
  • 6
  • 12

1 Answers1

3

Use longs for the product - this will be enough to hold the result of multiplying two integers.

You also will want to compute the modulo on each iteration so that you avoid overflow (this is safe to do from a mathematical perspective, as it doesn't change the result modulo 1000007 at the end).

You could also use BigIntegers if you wanted, but it would be much slower.

mikera
  • 105,238
  • 25
  • 256
  • 415