Matrix Fast Power

Source: Internet
Author: User

Reference: http://www.cnblogs.com/yan-boy/archive/2012/11/29/2795294.html

For a^n, we generally pass the n-1, but we can reduce the number of times by making simple improvements using the combination of matrix multiplication, for example, A*a*a*a*a*a = (a*a) * (a*a) * (a*a), which reduces the number of times from 5 to 3. So how do you get the minimum number of times to use the binding law?

The answer is: the combination of binary and dichotomy ideas

For example, a^21 = (a^16) * (a^4) * (a^1) (21=2^4+2^2+2^0), a^16 can be divided into two (a^8) * (a^8), a^8= (a^4) * (a^4) ....

Thus the number of factors can be reduced from N to log (n)

#include <stdio.h>#include<stdlib.h>#include<string.h>#include<time.h>#defineN 100#definell Long Longstructmat{ll mat[n][n];};voidShowmat (Mat a) { for(intI=0;i<3; i++)    {         for(intj=0;j<3; j + +) printf ("%lld", A.mat[i][j]); printf ("\ n"); }}voidInit (Mat &b)//initialized to the unit matrix, to reference{    intI, j, K;  for(i =0; I <3; ++i) { for(j =0; J <3; ++j) {B.mat[i][j]= (i = = j);//a shorthand notation}}}mat Matmul (Mat A,mat b) {mat C; memset (C.mat,0,sizeof(C.mat)); intI, j, K;  for(i =0; I <3; ++i) { for(j =0; J <3; ++j) { for(k =0; K <3; ++k) {C.mat[i][j]+ = a.mat[i][k] *B.mat[k][j]; }        }    }    returnC;} Mat MATLAB (Mat A,intN//Core Code, example a^156= (a^4) * (a^8) * (a^16) * (a^128){Mat B;    Init (b);  while(n) {if(n&1) b=Matmul (b,a); N>>=1;//Move RightA =Matmul (a,a); }    returnb;}intMain () {intN;    Mat A, B; scanf ("%d",&N); memset (A.mat,0,sizeof(A.mat)); memset (B.mat,0,sizeof(B.mat)); //generating three-dimensional random matricesSrand (Time (0));//Random seed---stdlib.h     for(intI=0;i<3; i++)         for(intj=0;j<3; j + +) A.mat[i][j]= rand ()% -; printf ("the random matrix is: \ n");    Showmat (a); b=MATLAB (a,n); printf ("the resulting matrix of%d powers is: \ n", N);    Showmat (b); return 0;}

Matrix Fast Power

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.