Fast power with large numbers modulo product

Fast power:

A n calculated value of p ^%, how to count it? Of course, direct operator may overflow. We have a lemma:. (A * b)% p = ((a% p) * (b% p))% p to merge on the index in this lemma to obtain fast power algorithm.

Specifically, there are two approaches, one is a reduced value, to prevent overflow, one is to reduce the b value, speed is calculated.

How to reduce a value? a = a% p, the value of a put down p or less. B for it, we find that, (a% p) * (a% p) = (a ^ 2)% p, if a ^ n-th power n is an even number, a ^ (2m)% p = ((a ^ 2 ) ^ m)% p, if n is odd, on the first by a single a, and the rest is an even number, and n is an even number so that the n can be reduced by half, thereby reducing the size of b.

Multiply large numbers modulo:

Calculation of (a * b)% p how to do? ((A% p) * (b% p))% p will still overflow.

The following uses an idea, and above magical powers to quickly have the same purpose, as the binary representation b.

For chestnut: 4 * 13% p, as a 4 * 1101 (2)% p, in fact, represents the 4 * (1 + 1 * 3 * 2 ^ 2 ^ 2 + 2 ^ 0 * 1 * 2 + 1 ^ 0)% p, then we put b as at the time of binary calculations, if the last bit is a binary 1, it means that one should take more than a ride, not a zero illustrate a ride, from low began the binary type b right, while a multiplied by 2, is equivalent to the square of the base, supra formula reasons.

Code:

. 1 #include <the iostream>
 2  the using  namespace STD;
 . 3  Long  Long q_mod ( Long  Long a, Long  Long n-, Long  Long P)
 . 4  {
 . 5      a = a% P;
 . 6      // First, a drop size 
. 7      Long  Long SUM = 1 ; // record the results 
. 8      the while (n-)
 . 9      {
 10          IF (& n- 1 )
 . 11          {
 12 is             = SUM (SUM * a)% n; // separate out when multiplied by n is an odd 
13 is          }
 14          a = (a * a)% P; // combined n a drop size of 
15          n / = 2 ;
 16      }
 . 17      return SUM;
 18 is  }
 . 19  Long  Long q_mul ( Long  Long A, Long  Long B, Long  Long P)
 20 is  {
 21 is      Long  Long SUM = 0 ;
 22 is      the while (B)
 23 is      {
 24          IF(b & . 1 ) // if b is zero binary end 
25          {
 26 is              (A = SUM +) =% P; // A to be added modulo 
27          }
 28          (A = << . 1 )% = P; // 2 corresponds to continuously increase the number of bits by a 
29          b >> = . 1 ; // the right b 
30      }
 31 is      return SUM;
 32 }

Can be found both very similar, the difference lies in the difference between the initial value and the calculation result variables of plus and multiplication.

Reference article:

It is quite clear a few written:

Cong six small, ACM algorithm: Fast modulo exponentiation (detail), https: //blog.csdn.net/dbc_121/article/details/77646508

ygeloutingyu, large numbers multiplication modulo operation (binary) , HTTPS: //www.cnblogs.com/geloutingyu/p/5886626.html

Guess you like

Origin www.cnblogs.com/zhanhonhao/p/11257424.html