Cod sursa(job #2434068)

Utilizator HelloWorldBogdan Rizescu HelloWorld Data 30 iunie 2019 15:41:51
Problema Ridicare la putere in timp logaritmic Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <cstdio>
using namespace std;
#define M 1999999973
#define ll long long
ll n,p;
ll pow(ll x,ll n)
{
    ll rez=1;
    while (n)
    {
        if (n & 1) rez=(rez*x)%M;
        x=(x*x)%M;
        n=n/2;
    }
    return rez;
    /// Little formal proof for why it works :
    /// n = power at which x is raised, n = b0*2^0 + b1*2^1 + b2*2^2 + ... + bk*2^k
    /// x^n = x^(b0*2^0 + b1*2^1 + b2*2^2 + ... + bk*2^k) = (x^(2^0))^b0 * (x^(2^1))^b1 * (x^(2^2))^b2 * ... * (x^(2^k))^bk
    /// A term contributes to the result only if bi is 1, since if bi is 0, then the term becomes 1, because it's (x^((2^k*0))) so it is x^0 which is equal to 1;
    /// source for proof : https://mpark.github.io/programming/2014/08/18/exponentiation-by-squaring/
}
int main()
{
    freopen("lgput.in","r",stdin);
    freopen("lgput.out","w",stdout);
    scanf("%ld%ld",&n,&p);
    printf("%ld",pow(n,p)%M);
}