Integer power quick modulo

Source: Internet
Author: User

The calculation method must be simplified because the exponential result of an integer is large and may be far beyond the scope of computer processing.

Modulo properties: (A * B) mod m = (a mod m) * (B mod m) mod m,

 

The principle of quick search for integer power is as follows:

For example, to evaluate m ^ N, just expand N in binary format: for example, n = A0 * 2 ^ 0 + A1 * 2 ^ 1 + ..... + AK * 2 ^ K;

 

The quick power method is as follows:

 

Long long fastpow (int m, int N) <br/>{< br/> long res = 1; <br/> for (; n> 1) <br/> {<br/> If (N & 1) <br/> res * = m; <br/> M * = m; <br/>}</P> <p> return res; </P> <p>}

 

The method for quickly modulo integer power is similar to the above:

CodeAs follows:

 

 

Long long powermod (long a, int B, int K) <br/> {// (a ^ B) % K <br/> long TMP =, ret = 1; <br/> for (; B; B> 1) <br/>{< br/> If (B & 1) <br/> ret = (Ret * TMP) % K; // perform the modulo operation in each step. <br/> TMP = (TMP * TMP) % K; <br/>}< br/> return ret; <br/>}< br/>

 

 

 

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.