2

I have to find the modulo of division of this numbers:

239^(10^9) and 10^9 + 13

239^(10^9) and 10^9 + 15

... etc up to 1001;

Using only native libraries in c++. How to do that? As you can see, the first number is about 3 billion symbols.

I tried finding the length of modulo periods, but they are mush longer, than 10, and even unsigned long long int can't deal with such big numbers (239^10). Also I think that "big numbers" algorithms (storing a number as an array) will not work for me too (500*10^9) is too much operations.

BTW, this is supposed to work less, than in 5 hours.

pomo_mondreganto
  • 2,028
  • 2
  • 28
  • 56
  • 2
    *Is there a way to do that?* Most likely yes but that doesn't help you, does it? – R Sahu May 14 '15 at 18:09
  • @RSahu, yes, how did you guess?!? – pomo_mondreganto May 14 '15 at 18:10
  • 2
    See [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) – R Sahu May 14 '15 at 18:10
  • 3
    You should look into [modular exponentiation](https://en.wikipedia.org/wiki/Modular_exponentiation). It's exactly what you need. The trick is to *not* calculate the result then divide. – Mr. Llama May 14 '15 at 18:13
  • 1
    It should calculate pretty much immediately (i.e. in milliseconds) if you use "Right-to-left binary method" from the Wiki link. (You have only 500 different modulos, and the exponent is only 2^30, right?) – Kolmar May 14 '15 at 18:17
  • Modulo periods only work for prime numbers, some of the numbers in the series 10^9 + 13 ... to 1001 are not prime numbers. The answer below should work. – rcgldr May 14 '15 at 18:50
  • @Kolmar, yes, I have written this algorithm and it works perfectly (about 0.5 seconds to calculate each number) – pomo_mondreganto May 15 '15 at 05:00

1 Answers1

6

We know that:

(A*B) % MOD = ((A % MOD) * (B % MOD)) % MOD

So

(A^n) % MOD = (((A ^ (n/2)) % MOD) * ((A ^ (n/2)) % MOD)) % MOD;

And we can do it recursively.

So, here is our function:

int cal(int pow, int val, int MOD){
   if(pow == 0)
      return 1;
   int v = cal(pow/2, val, MOD);
   if(pow % 2 == 0)
      return (v*v) % MOD; 
   else
      return (((v*val) % MOD) * v) % MOD;
}
Pham Trung
  • 11,204
  • 2
  • 24
  • 43