# Upper power modulo

Source: Internet
Author: User

The main idea is to use a formula:A * B % C = (a % C) * (B % C) % C

Basic concepts and ideas

Operations on the form such as a ^ B mod m (B is generally large), but a, B, and m are all within the long range. Algorithm The main idea is to divide and conquer. Divide large problems into several similar small problems! The specific implementation is to use recursive methods! For example, 2 ^ 100mod 3, if we calculate the value of 2 ^ 100 first and then modulo 3, it is more difficult! We can change 100 to 2 ^ 100 = (2 ^ 50) ^ 2 = (2 ^ 25) ^ 2) ^ 2 = (2 ^ 1) ^ 2) ^ 2 )...) ^ 2 if we have obtained the value of 250 mod 3, we can easily get the value of 2 ^ 100mod 3. Continue with the analysis according to the above method... The final result will surely be 2 ^ 1mod 3! This is easy to handle! This is the recursive boundary. Now we can return the value of 2 mod 3! Another problem is that there are two cases of time-sharing! 2 ^ 100 = (2 ^ 50) 2,100 is an even number 2 ^ 99 = (2 ^ 49) 2*2, 99 is an odd number. In the second case, the base number must be higher than that in the first case.

Recursive AlgorithmsCodeAs follows:

` 1  Long MoD ( Long A, Long B, Long  C)  2   {  3       Long  Ans;  4       If (! B) Return   1  ;  5       Else  If (B = 1) Return A % C;  6       Else Ans = Mod (a, B/ 2  , C );  7 Ans = (ANS * ans) % C;  8       If (B & 1 ) Ans = (ANS * (a % C) % C;  9       Return Ans;  10 }`

Another efficient algorithm is to replace recursive algorithms with loops.

` 1   Long Mod_loop ( Long A, Long B, Long  C)  2   {  3       Long Ret = 1 , TEM =A;  4       While  (B)  5   {  6           If (B & 1 ) Ret = RET * TEM % C;  7 TEM = TEM * TEM % C;  8 B> = 1  ;  9  }  10       Return  RET;  11 }`

Related Keywords:

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.