Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating (a^b)%MOD

Tags:

c++

math

I want to code for calculating the value of pow(a,b)%MOD. I use C++ to code.

But the problem is the value of b can be very large. I know the log(b) time complexity method. But, the value of b might not fit in the data type "long long" of C++. For example b can be 1000000000 th Fibonacci number. Exact calculation of such a big number is itself, not possible (in time limits).

P.S. :

  • pow(a,b) means a*a*a*a*... b times.
  • X % MOD means the remainder obtained on dividing X by MOD.
like image 430
Gurpreet Singh Avatar asked Jun 30 '12 07:06

Gurpreet Singh


People also ask

How do you calculate AB mod?

Let's look at how this relates to calculating modulus. As we said, a mod b is simply an expression representing the remainder when we divide a by b. Therefore, if a / b = q remainder r, then a mod b = r.

What does a ≡ b mod m mean?

The first was defined in a previous lecture: a mod b denotes the remainder when we divide a by b. The "mod m" in a ≡ b (mod m) is a note on the side of the equation indicating what we mean when we say "≡" Fact: These two uses of "mod" are quite related: a ≡ b (mod m) if and only if a mod m = b mod m.

What does a ≡ b mod n mean?

For a positive integer n, two integers a and b are said to be congruent modulo n (or a is congruent to b modulo n), if a and b have the same remainder when divided by n (or equivalently if a − b is divisible by n ). It can be expressed as a ≡ b mod n. n is called the modulus.


1 Answers

That's a typical task. Please (or, really, PLEASE!) read about the Euler's totient function.

And then the Euler's theorem.

The thing is you can dramatically reduce a^b to a^(b % phi(MOD)). Yes, you will need some kind of an integer factorization method, but still, no crazy ideas about actually calculating the power needed.

We did such samples by hand in my youth :) Even when the numbers where far beyond 32/64 bit range.

EDIT: Well, you live and learn. In 2008 the result is obtained:

"The totient is the discrete Fourier transform of the gcd: (Schramm (2008))"

So to calculate phi(b) one does not need to know its factors.

EDIT(2):

And the Carmichael's function is what you need to calculate to get the correct answer for any a, b and MOD.

like image 56
Viktor Latypov Avatar answered Sep 27 '22 18:09

Viktor Latypov