Saturday, October 22, 2011

[UVa] 374 - Big Mod

Used a recursive method from Art of Programming Contest
LL bigMod(LL b, LL p, LL m)
{
    if (!p) return 1;
    else if (!(p&0x01)) return power(bigMod(b,p/2,m),2)%m;
    else return (b%m * bigMod(b,p-1,m))%m;
}

#include <stdio.h>
#define LL long
LL power(LL a, LL p)
{
    int ret=1;
    while (p--)
        ret*=a;
    return ret;
}
LL bigMod(LL b, LL p, LL m)
{
    if (!p) return 1;
    else if (!(p&0x01)) return power(bigMod(b,p/2,m),2)%m;
    else return (b%m * bigMod(b,p-1,m))%m;
}

int main()
{
    LL b, p, m;
    while (scanf("%ld %ld %ld",&b,&p,&m)==3)
    {
       printf("%ld\n",bigMod(b,p,m));
    }
    return 0;
}

No comments:

Post a Comment

Post your comment here. If you want to say something about programming problems, scripts, software etc, please try to be as descriptive as possible.

Connect Rapoo MT750S with Linux (Tested on Manjaro)

 I bought this obvious copy of MX Master 2S in hopes of having the device switching functionality along with a lightweight body because I ha...