Power of large numbers
How much does Hackerland coach pay to get Cristiano Ronaldo to play for his team?. Problem statement here.
Difficulty Level
Medium
Required Knowledge
Fermat’s Little Theorem, Fast Modulo Exponentiation, Large digits Arithmetic using arrays.
Time Complexity
O(N) for Step 1 O(logN) for exponent step.
Approach
Given two large numbers A and B, we have to find AB % M
AB can be written as A*A*A….. B times. So we can simply take A%M. But since A is a large number we can store it in a long array and perform modulo digit by digit.
Since x*10+y %M = ((x%M)*10 + y)%M we can iteratively do for all digits.
Next we note that 109+7 is a prime number.
According to Fermat’s Little Theorm, Ap-1 ≡ 1 % p , where p is a prime number.
Hence we take B%(p-1) => B%(109+6).
Now we have two 9 digit numbers which we solve using fast exponentiation.
Setter’s Code :
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<bits/stdc++.h>
using namespace std;
#define MOD 1000000007
int A[100009];
int B[100009];
long long int expn(long long int N, long long int K)
{
if(K==0) return 1;
if(K==1) return N%MOD;
if(K%2 ==0)
{
long long int temp = expn(N,K/2);
return (temp*temp)%MOD;
}
else
{
long long int temp = expn(N,K/2);
temp = (temp*temp)%MOD;
return (temp*N)%MOD;
}
}
int main()
{
int T,i;
string str1,str2;
cin>>T;
assert(1<=T);
assert(T<=10);
while(T--)
{
long long int M = 1000000007;
long long int N = 1000000006;
long long int temp1,temp2;
cin>>str1>>str2;
for(i=0 ; i<str1.length() ;i++)
{
A[i] = str1[i] - '0' ;
}
for(i=0 ; i<str2.length() ;i++)
{
B[i] = str2[i] - '0' ;
}
assert(str1[0]!='0');
assert(str2[0]!='0');
assert(str1.length() <=100000);
assert(str2.length() <= 100000);
temp1 = A[0] % M;
for(i=1 ; i< str1.length() ; i++)
{
temp1 = (10*temp1 + A[i] )% M;
}
temp2 = B[0] % N;
for(i=1 ; i< str2.length() ; i++)
{
temp2 = (10*temp2 + B[i] )% N;
}
//cout<<temp1<<" "<<temp2<<endl;
cout<<expn(temp1,temp2)<<endl;
}
return 0;
}
Tester’s Code
def pow_mod(x, y, z):
number = 1
while y:
if y & 1:
number = number * x % z
y >>= 1
x = x * x % z
return number
mod=10**9+7
t=input()
for i in range(0,t):
inp=map(int,raw_input().split(" "))
a=inp[0]
b=inp[1]
a=a%mod
b=b%(mod-1)
print pow_mod(a,b,mod)