Problem : Find the value of (abc)mod(109+7) where 1≤n≤105 and 1≤a,b,c≤109
In order to solve this problem, we need to understand the Fermat's little theorem:
If a is not divisible by p we can express as (a(p−1)≡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):
Then, reform equation (B) with equation (A):
Substitute equation (A) with 1:
=1d∗(ar)mod(p)=(ar)mod(p)where bc=d∗(p−1)+r, r is remainder of bc
Therefore, (abc)mod(p)=(a(bc)mod(p−1))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