Problem solution · Python

ABC293 E — Geometric Progression

ABC293 E — Geometric Progression: a Python solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to KATO-Hiro AtCoder Solutions.

Technique
Direct simulation
Source
KATO-Hiro AtCoder Solutions
Length
35 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For ABC293 E — Geometric Progression, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 35 lines of Python from the credited upstream file abc293_e.py.
  • The implementation visibly relies on ordered lookup.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from KATO-Hiro AtCoder Solutions by KATO-Hiro and is used under the CC0-1.0 licence.

Full codeABC293 E — Geometric Progression · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  def main():    import sys     input = sys.stdin.readline     a, x, m = map(int, input().split())     # ⚪︎: 等比数列の和    if a == 1:        # △: 与えられた式を愚直に計算すると、分子は1ではなくx        print(x % m)    else:        # △: mが素数でない場合への対処方法        # mod m * (a - 1)を取る        # See:        # https://atcoder.jp/contests/abc293/editorial/5966        # https://www.youtube.com/watch?v=O_ga06kO84Y         # b = a ** n、k = a - 1とおく        # 等比数列の和の式 % mは、(b / k) % m = rと言い換えられる        # q, r = divmod(b / k, m)であることを利用すると、b / k = m * q + r        # 両辺をk倍すると、b = (m * k) * q + r * k        # 両辺に対して、mod mkをとると、b % mk = r * k        # 両辺に対してkで割る        k = a - 1        ans = (pow(a, x, m * k) - 1) // k % m        print(ans)  if __name__ == "__main__":    main() 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗