Link:- https://www.hackerrank.com/challenges/power-of-large-numbers
Summary:
Given A and B.
Find (A^B)%(10^9+7)
Constraints:
1 <= T <= 10
1 <= A,B <= 10100000
A % (109 + 7) != 0
For Example:
Sample Input:
4
3 2
4 5
7 4
34534985349875439875439875349875 93475349759384754395743975349573495
Sample Output:
9
1024
2401
735851262
Logic:
(A^B)%MOD = (A%MOD)^B
Since A is very very large number can't be stored in int or long so using modulo technique bring A in the range of int or long as:
Let 'a' be an array contains digit of A so to construct A%MOD. Let A = 0
for i 0 to len(a):
A = (A*10 + a[i])%MOD
This gives A%MOD
Now B is also very very large but we can't apply same technique as we done in A as
(A%MOD)^B%MOD != (A%MOD)^(B%MOD)%MOD
So we use Fermet's Little Theorem which says:
where p is prime number.
divide by a both side
Since MOD = 10^9+7 is a prime number
we need to find A^B%MOD
so if B is divisible by (p-1) or (MOD-1) then B = (MOD-1)*x
so (A^((MOD-1)*x))%MOD = (A^(MOD-1)%MOD)^x%MOD = 1^x%MOD = 1
and if B is not divisible by (MOD-1) then B = (MOD-1)*x + y
so
(A^((MOD-1)*x+y))%MOD = ((A^(MOD-1)%MOD)^x)%MOD*(a^y)%MOD = 1^x*(a^y)%MOD
and y = B%(MOD-1)
so y can be computed as:
y = 0
b is an array contains digit of number B.
for i 0 to len(b)
y = (y*10 + b[i])%(MOD-1)
if y==0
answer = 1
else
answer = A^y%MOD
To View My Solution:
https://github.com/shivam04/codes/blob/master/hackerrank/math/number%20theory/medium/power-of-large-number.py
Summary:
Given A and B.
Find (A^B)%(10^9+7)
Constraints:
1 <= T <= 10
1 <= A,B <= 10100000
A % (109 + 7) != 0
For Example:
Sample Input:
4
3 2
4 5
7 4
34534985349875439875439875349875 93475349759384754395743975349573495
Sample Output:
9
1024
2401
735851262
Logic:
(A^B)%MOD = (A%MOD)^B
Since A is very very large number can't be stored in int or long so using modulo technique bring A in the range of int or long as:
Let 'a' be an array contains digit of A so to construct A%MOD. Let A = 0
for i 0 to len(a):
A = (A*10 + a[i])%MOD
This gives A%MOD
Now B is also very very large but we can't apply same technique as we done in A as
(A%MOD)^B%MOD != (A%MOD)^(B%MOD)%MOD
So we use Fermet's Little Theorem which says:
where p is prime number.
divide by a both side
Since MOD = 10^9+7 is a prime number
we need to find A^B%MOD
so if B is divisible by (p-1) or (MOD-1) then B = (MOD-1)*x
so (A^((MOD-1)*x))%MOD = (A^(MOD-1)%MOD)^x%MOD = 1^x%MOD = 1
and if B is not divisible by (MOD-1) then B = (MOD-1)*x + y
so
(A^((MOD-1)*x+y))%MOD = ((A^(MOD-1)%MOD)^x)%MOD*(a^y)%MOD = 1^x*(a^y)%MOD
and y = B%(MOD-1)
so y can be computed as:
y = 0
b is an array contains digit of number B.
for i 0 to len(b)
y = (y*10 + b[i])%(MOD-1)
if y==0
answer = 1
else
answer = A^y%MOD
To View My Solution:
https://github.com/shivam04/codes/blob/master/hackerrank/math/number%20theory/medium/power-of-large-number.py