Loading [MathJax]/jax/output/HTML-CSS/jax.js

Saturday, July 25, 2020

CSES Exponentiation II


Problem : Find the value of (abc)mod(109+7) where 1n105 and 1a,b,c109


In order to solve this problem, we need to understand the Fermat's little theorem:

(apa)mod(p) Where p is a prime number.

If a is not divisible by p we can express as (a(p1)1)mod(p)=1....(A)
Since 109+7=prime=p, I can rewrite (abc)mod(109+7) into  (abc)mod(p).....(B)

Then, reform equation (B) with equation (A):

(abc)mod(p)=(ad(p1)+r)mod(p)

Substitute equation (A) with 1:

=1d(ar)mod(p)=(ar)mod(p)where bc=d(p1)+r, r is remainder of bc

Therefore, (abc)mod(p)=(a(bc)mod(p1))mod(p) where p is a prime, p=109+7


C++ Code Implementation:

#include <iostream>

using namespace std;
typedef unsigned long long int lld;
lld prime = 1e9+7;

lld my_pow(lld a, lld b, lld m)
{
    lld result = 1;
    lld intermediate = a;

    if(b==1) return a;

    while(b)
    {
        if(b&1)
        {
            result*=intermediate;
            result%=m;
        }
        intermediate*=intermediate;
        intermediate%=m;
        b>>=1;
    }

    return result;
}

int main()
{
    int n;
    cin>>n;

    for(int i=0;i<n;i++)
    {
        lld a,b,c;
        cin>>a>>b>>c;
        lld tmp = my_pow(b, c, prime-1);
        cout<<my_pow(a, tmp, prime)<<endl;
    }

    return 0;
}


No comments:

Post a Comment

CSES Subtree Queries

You are given a rooted tree consisting of n nodes. The nodes are numbered 1,2,…,n, and node 1 is the root. Each node has a value. Your...