Fast multiplication, fast power (Matrix fast Power)

Source: Internet
Author: User

When the MoD is a large number p, there are times when multiplication may explode long, using fast multiply or fast power.

Reference: http://www.cnblogs.com/whywhy/p/5066730.html

First on the template:

Quick multiply:

ll multi (ll a,ll b,ll m) {    ll ans=0;      while (b)    {        if(b&1) (ans+=a)%= m;        (A=a*2)%= m;        b/=2;    }     return ans;}

Fast power:

ll Pow_mod (ll a,ll b,ll m) {    ll res=1;      while (b)    {        if(b&1) Res=multi (res,a,m);  // We're going to use a fast ride        here. A=multi (a,a,m);        b/=2;    }     return Res;}

Quick Multiply + fast power hdu topic link (puzzle)

Another is: Matrix fast power, according to the topic analysis, and then establish the relevant matrix, and then use the fast power;

Matrix Fast Power:

Node mult (node A,node b)//The calculation of the matrix{node T;  for(intI=0;i<2; i++)         for(intj=0;j<2; j + +) {T.m[i][j]=0;  for(intp=0;p <2;p + +) T.m[i][j]= ((T.m[i][j]+a.m[i][p]*b.m[p][j])%mod+mod)%MOD; }    returnt;}voidPow_mod (Long LongN) {original.m[0][0]=1, original.m[0][1]=-1; original.m[1][0]=1, original.m[1][1]=0; ans.m[0][0]=ans.m[1][1]=1; ans.m[0][1]=ans.m[1][0]=0;//Initialize ans to 2-order matrix E     while(n) {if(n%2==1) ans=mult (ans,original); Original=mult (original,original); N/=2; }}

Two-way matrix fast power:

CF 450B (solution) POJ 3070 Fibonacci Matrix Rapid Power New method

Fast multiplication, fast power (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.