Given two positive integers a and a large positive integer array b representing an integer b containing digits from b[0] to b[n-1] (i.e., b is expressed as an array). Calculate a raised to the power b mod 1337.
Essentially, the task is to compute (a^{b} \mod 1337), where (b) is a large number represented by an integer array.
a always a positive integer?
a is always a positive integer.b?
b are digits, so each element is between 0 and 9.b be large (e.g., tens of thousands of elements)?
b can be very large, which is why directly computing the power is not feasible.a or b is zero?
a is 0 and b is not zero, the answer should be 0 (i.e., 0^b = 0 for any b != 0). If b is zero, a ^ b should be 1 (i.e., a^0 = 1 for any a != 0).To solve this problem efficiently:
b.b is an array, e.g., [1, 2, 3], it represents the number 123.Let’s implement the solution:
def superPow(a, b):
MOD = 1337
# Helper function to compute (x ^ y) % mod using iterative squaring
def power_mod(x, y, mod):
result = 1
x = x % mod # Update x if it is more than or equal to mod
while y > 0:
if y % 2 == 1: # If y is odd, multiply x with result
result = (result * x) % mod
y = y >> 1 # y = y // 2
x = (x * x) % mod # Change x to x^2
return result
# Reduce problem using the properties of modulus
a %= MOD
result = 1
for digit in b:
result = power_mod(result, 10, MOD) * power_mod(a, digit, MOD) % MOD
return result
# Example usage:
a = 2
b = [1, 0]
print(superPow(a, b)) # Output: 1024
The time complexity of this algorithm is O(n * log(10)), where n is the number of digits in the array b and log(10) arises from the power_mod function.
b:
b, adjust the current power result using the previous result taken to the power of 10 (because each new digit represents the next power of 10).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?