Integer fast multiplication/fast Power + matrix fast power +strassen algorithm

Source: Internet
Author: User
Tags explode

The fast power algorithm can be said to be a kind of ACM competition is necessary, and is also a very basic type of algorithm, given that I have been learning more fragmented, so today with this post summed up

Fast multiplication usually has two types of applications: First, integer operation, calculation (A*B) mod C second, matrix fast multiplication

integer operations: (Fast multiplication, fast power)

Let's start with basic mathematical knowledge:

(a*b) MoD c = = ((a mod c) * (b mod c)) MoD C//This last mod C is to ensure that the result does not exceed C

for 2 binary, 2n is available 1 followed by n x zero, for 8, the available formula I+3*j = = N (where 0<= i <=2), for 16 binary, available i+4*j==n (0 <= i <=3) to be calculated, expressed in the form of 2 i is followed by a J 0.

Next, let's describe the idea of fast multiplication as simple as possible:

A*b

The basic idea of fast multiplication is the combination of binary and multiply distribution laws, (I can't help thinking that floating-point numbers do not meet the binding law, serious spit groove!!!) ╮ (╯-╰) ╭), for example, 2 = = (1101)2 , 4*13 equalsto the 2(1101), with the distribution of the law to expand the 4*13 = = (1000+100+1), we are not difficult to observe, The fast power can be determined by determining if the current bit (bit) is 1 or 0, and whether or not the sum operation needs to be done, and each time it moves to the next bit (bit), the ANS is manipulated, waiting for the sum. Since dividing by 2 is equivalent to the displacement operation, this can also be seen as the application of dichotomy, which divides B into two to reduce unnecessary operations, with the time complexity of log (n).

A^b

The fast power can be seen as a special case of fast multiplication, in the fast power, we no longer operate ans, because the meaning of B in a^b has changed from the multiplier to the exponent, but we can still write B as a binary, for example: At this time, we will 4*13 to 4^13,13= (1101) 2, binary 13 write open we get (1000+100+1), note that here all binary is exponential, the addition of the exponent means that the base is multiplied, so there is 4^13 = = 48 * 44 * 41. Noting the twice-fold relationship between the indices, we can use a few variables to complete the algorithm. In this way, we will improve the algorithm to O (LOGN) by using an O (n) algorithm that would otherwise be used for loops.

As a rule, give a code implementation that is as concise and efficient as possible (all the following int can be replaced with a long long)

First, the implementation of the fast multiplication is given:

1//fast multiplication 2 int qmul (int a,int b) {//Based on data range selectable long long 3     int ans=0;4 while     (b) {5         if (b&1) ans+=a;//bitwise AND Completion bits 1 Judgment 6         b>>=1;a<<=1;//bit operation instead of/2 and *27     }8     return ans;9}

If fast multiplication is involved, you need to make some minor changes

The mathematical principles on which the changes are based, please refer to the mathematical knowledge shown in the red font

1//fast multiplication modulo 2 int qmul_mod (int a,int b,int MoD) {3     int ans=0;4 while     (b) {5         if ((b%=mod) &1) ans+=a%=mod;// This requires B%=mod and A%=mod 6         b>>=1;a<<=1;7     }8     return ans%mod;  Ans also need to modulo mod 9}

Next is the implementation of the Fast power:

1//Fast power a^b  2 int qpow (int a,int b) {3     if (a==0) return 0;//This is a pit, the school game has been pit, many online implementations have not written this point 4     int ans=1; 5 while     (b         the difference between {6 if (b&1) ans*=a;//and fast multiplication 7         b>>=1;a*=a;//difference, ibid. 8     } 9     

And a fast power that contains a modulo:

int qpow_mod (int a,int b,int mod) {    if (a==0) return 0;    int Ans=1;    while (b) {        if (b&1) ans= (ans%mod) * (A%MOD);//If it is determined that the data will not explode, it can be written as ans*=a%=mod;        b>>=1;a*=a%=mod;//is equivalent to a= (a%mod) * (A%mod), and a modulo operation is replaced by an assignment, improving efficiency    }    return ans%mod;//data will not explode, The operation is equivalent to the repeated ans%mod in the 5th}

If we have further requirements for performance, that is to reduce the modulo operation, then we need to make sure that the data range does not explode

Under this premise, we can only use the original 1/4 modulus calculation to complete the fast power

int qpow_mod (int a,int b,int mod) {    if (!a) return 0;    int Ans=1;    while (b) {        if (b&1) ans*=a%=mod;//Here there is only one        b>>=1;a*=a;//modulo operation has no    }    return ans%mod;}

These days looking for a long time, finally found the pure integer fast power problem, according to the Convention, to a wave Portal:

poj1995:http://poj.org/problem?id=1995

This question ... There's nothing to say, but be aware that with 1/4 modulo arithmetic, the data will explode, so you have to write a complete modulo operation, so the program will be slower ... Woo-woo, 63ms water over, this is the slowest I have done now, if the great God knows how to drop it in 16ms and below, please contact me thank you ~o (* ̄▽ ̄*) ブ

The implementation code is as follows:

1 #include <cstdio> 2 int z,a,b,m,h,sum; 3 int qpow_mod (int a,int b,int MoD) {4     if (!a) return 0; 5     int ans=1; 6 while     (b) {7         if (b&1) ans=ans%mod* (A%=MOD); 8         b>>=1;a=a%mod* (a%mod); 9     }10     return ans%mod;11}12 int main () {     scanf ("%d", &z);     while (z--) {         scanf ("%d%d", &m,&h), sum=0;16 while         (h--) {             scanf ("%d%d", &a,&b); 18             Sum+=qpow_mod (a,b,m);             sum%=m;20         }21         printf ("%d\n", sum);     }23}
View Code

First update to this, there is time to update the matrix of the Strassen algorithm and matrix fast power, you see later ('? ') )

2016-06-13 16:47:56

Hello, everyone, I'm back.

Second, matrix operation: (Fast power) (Strassen algorithm is empty)

The fast power operation of the Matrix, in fact, the idea and the above integer fast power is the same, the exponent of two points, but we for the fast power itself, may be written as a function, or can be written as operator overloading, so here I write the operator overload, after all, the overloading of the training to practice a little more practice

First we can define a matrix data structure, or we can directly use a two-dimensional array

1 #define N 1002 struct matrix{3     int m[n][n];4};

Then we overload the ^ operator to complete the fast power of the B power of the matrix M

Here for my own code habits, I overloaded * and *= two kinds of operators, of course, at the time of writing kneeling in the forgot to write function declaration, after all, C + + is not Java, for the order of function declarations are dependent, so~ you remember to write function declaration yo

The code is as follows

1//matrix data structure 2 struct matrix{3     int m[n][n]; 4}; 5 Matrix operator * (matrix, matrix);//Overload declaration 6 matrix operator *= (Mat Rix,matrix); 7 matrix operator ^ (Matrix A,int B) {8     matrix ans; 9 for     (int i=0;i<n;i++) ten for         (int j=0;j<n;j++) ans.m[ I][j]= (I==J);//Initialize to the unit matrix one     if (b&1) ans*=a;12     b>>=1;a*=a;13     return ans;14}15 matrix operator * ( Const matrix A,const matrix B) {//naive matrix multiplication-matrix     ans;17 for     (int i=0;i<n;i++) + for         (int j=0;j<n;j++) for             (int k=0;k<n;k++)                 ans.m[i][j]=a.m[i][k]+b.m[k][j];21     return ans;22}23 matrix operator *= ( Matrix A,const matrix B) {     return a=b*b;25}

Of course, when necessary, I will update a wave Strassen algorithm, considering in many cases, the Strassen algorithm will reduce the speed of the matrix operation, so we first come here ~ bye (ˇ?ˇ)

Integer fast multiplication/fast Power + matrix fast power +strassen algorithm (RPM)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.