Given two very large integers,assume the length=1,000,000 digits,how will you compute $a^b \mod 10^7$.Since the two numbers are large, of course the value of a^b will be large. So,we find only the last 7 digits using modulus $10^7$. I came across this solution where $\mod=10^7$.
#include<stdio.h>
ll ppow(ll b,ll p)
{
if(p==0) return 1;
if(b==1) return 1;
if(p%2==0)
{
ll res=ppow(b,p/2);
return (res*res)%mod;
}
return (b*ppow(b,p-1))%mod;
}
char A[100001],B[100001];
void solve()
{
scanf("%s %s",A,B);
ll a=0;
for(int i=0;A[i]!='\0';i++)
{
a=(10*a+A[i]-'0')%mod;
}
ll res=1;
for(int i=0;B[i]!='\0';i++)
{
res=(ppow(res,10)*ppow(a,B[i]-'0'))%mod;
}
printf("%lld\n",res);
}
int main()
{
int t;
read(t);
while(t--)
solve();
}
I can see that some beautiful trick is done using modulus.But,i'm not able to figure out that trick :(. I'm trying this from today morning. But i'm not able to figure this out. Can somebody give me an insight how this solution works ?
I know these types of problems can be easily done using PYTHON.But just want to know the math behind it .
Thanks.
modso we are left to guess that it might be defined as some positive integer elsewhere... – abiessu Nov 25 '13 at 18:35