HDU 1420 Montgomery power modulo Algorithm

Source: Internet
Author: User
Prepared for New Acmerhttp: // acm.hdu.edu.cn/showproblem.php? Pid = 1420 Montgomery power mode idea:

In power modulo operations, a power modulo operation is usually used to convert a power modulo operation to a Multiplication Modulo operation. There are two formulas:

1) a * B % n = (a % n) * (B % n) % n

2) (a + B) % n = (a % n + B % n) % n

When we calculate D = C ^ 15% N, there are:

C1 = C * C % N = C ^ 2% N

C2 = C1 * C % N = C ^ 3% N

C3 = C2 * C2 % N = C ^ 6% N

C4 = C3 * C % N = C ^ 7% N

C5 = C4 * C4 % N = C ^ 14% N

C6 = C5 * C % N = C ^ 15% N

Therefore, power modulo operations can be converted to Multiplication Modulo operations. Continue to see, we will find that D = C ^ E % N is required to know when E can be divided into 2, and do not need to perform the operations of one or two again, you only need to verify whether the binary bit of E is 0 or 1.

Code:

#include <cstdio>__int64 fun(__int64 A,__int64 B,__int64 C){__int64 k = 1; A%=C;while(B>=1){if((B&1)!=0)k = (k*A)%C;        B>>= 1;A = A*A%C;}return k;}int main(int argc, char *argv[]){int n;scanf("%d",&n);__int64 A,B,C;while(n--){scanf("%I64d%I64d%I64d",&A,&B,&C);printf("%I64d\n",fun(A,B,C));}return 0;}
Common Code:
# Include <iostream> # include <cstdio> # include <cstring> # include <algorithm> # include <cmath> # include <string> # include <iomanip> using namespace std; int main (int argc, char * argv []) {int n; scanf ("% d", & n); int A, B, C; while (n --) {scanf ("% d", & A, & B, & C); _ int64 ans = 1; for (int I = 1; I <= B; I ++) {ans * = A; ans % = C; // note that the remainder of the request is required. Otherwise, data overflow is easy ;} printf ("% I64d \ n", ans);} return 0 ;}

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.