Skip to content

372. Super Pow 👎

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int superPow(int a, vector<int>& b) {
    int ans = 1;

    a %= kMod;
    for (const int i : b)
      ans = modPow(ans, 10) * modPow(a, i) % kMod;

    return ans;
  }

 private:
  static constexpr int kMod = 1337;

  long modPow(long x, long n) {
    if (n == 0)
      return 1;
    if (n % 2 == 1)
      return x * modPow(x % kMod, (n - 1)) % kMod;
    return modPow(x * x % kMod, (n / 2)) % kMod;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int superPow(int a, int[] b) {
    int ans = 1;

    a %= kMod;
    for (final int i : b)
      ans = modPow(ans, 10) * modPow(a, i) % kMod;

    return ans;
  }

  private static final int kMod = 1337;

  private int modPow(int x, int n) {
    if (n == 0)
      return 1;
    if (n % 2 == 1)
      return x * modPow(x % kMod, (n - 1)) % kMod;
    return modPow(x * x % kMod, (n / 2)) % kMod;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def superPow(self, a: int, b: list[int]) -> int:
    kMod = 1337
    ans = 1

    for i in b:
      ans = pow(ans, 10, kMod) * pow(a, i, kMod)

    return ans % kMod