Fast Power algorithm, power algorithm

Source: Internet
Author: User

Fast Power algorithm, power algorithm

2016.1.25 my first article

 

 

When a simple algorithm needs O (B) time complexity for computation operations such as AB, B is obviously not desirable when B is large, so we hope to find a fast algorithm for calculation, especially when the answer is required to be modulo.

For simple algorithms, we have

Ans = 1;

For (int I = 1; I <= B; I ++) (ans * = a) % = mod;

We can simply optimize it by adding a % = mod before the loop;

 

When B is an even number, we can do this.

Ans = 1;

For (int I = 1; I <= B/2; I ++) (ans * = a) % = mod;

(Ans * = ans) % = mod;

Special Judgment is required when B is an odd number.

Ans = 1;

For (int I = 1; I <= B/2; I ++) (ans * = a) % = mod;

(Ans * = ans) % = mod;

If (B & 1) (ans * = a) % = mod;

In this way, the time can be halved.

 

We can even do this.

Ans = 1;

For (int I = 1; I <= B/4; I ++)

{

(Ans * = a) % = mod;

}

(Ans * = ans) % = mod;

(Ans * = ans) % = mod;

If (B & 1) (ans * = a) % = mod;

If (B/2) & 1) (ans * = a * a) % = mod;

 

We will naturally think that if the time can be halved, halved, and halved, the time complexity can be reduced to O (log n ).

The implementation method is also very simple, that is, the above steps are iterated multiple times.

The Code is as follows:

Int ans = 1; a % = mod; while (B) {if (B & 1) (ans * = a) % = mod; B/= 2; // you can know that any number greater than 1 can reach B = 1 in this step multiple times, so you don't have to worry that ans won't get a value (a * = a) at last) % = mod ;}View Code

 

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.