Fast Power modulo & GCD

Source: Internet
Author: User
long long mod_pow(int a,int n,int p){    long long ret=1;    long long A=a;    while(n)    {        if (n & 1)            ret=(ret*A)%p;        A=(A*A)%p;        n>>=1;    }    return ret;}

Quick power modulo to prevent overflow in the middle:

Ll modular_multi (ll a, LL B, ll c) {// a * B % C ll res, temp; Res = 0, temp = A % C; while (B) {If (B & 1) {res + = temp; If (RES> = c) {res-= C ;}} temp <= 1; if (temp> = c) {temp-= C;} B >>= 1;} return res;} ll modular_exp (ll a, LL B, ll C) {// a ^ B % C cannot be changed to mod_pow, and an overflow occurs in the middle. The template still works like LL res, temp; Res = 1% C, temp = A % C; while (B) {If (B & 1) {res = modular_multi (Res, temp, c);} temp = modular_multi (temp, temp, C ); B >>= 1 ;}return res ;}

LL gcd(LL a, LL b) {    if (a < b) {        a ^= b, b ^= a, a ^= b;    }    if (b == 0) {        return a;    }    if (!(a & 1) && !(b & 1))        return gcd(a >> 1, b >> 1) << 1;    else if (!(b & 1))        return gcd(a, b >> 1);    else if (!(a & 1))        return gcd(a >> 1, b);    else        return gcd(b, a - b);}

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.