ARC113 B - A^B^C

備忘録

問題

atcoder.jp

回答

import sys
import os
import math
import bisect
import itertools
import collections
import heapq
import queue
import array
import time
import datetime

# 時々使う
# import numpy as np
# from decimal import Decimal, ROUND_HALF_UP
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall

# 再帰の制限設定
sys.setrecursionlimit(10000000)


def ii(): return int(sys.stdin.buffer.readline().rstrip())
def il(): return list(map(int, sys.stdin.buffer.readline().split()))
def it(): return tuple(map(int, sys.stdin.buffer.readline().split()))
def fl(): return list(map(float, sys.stdin.buffer.readline().split()))
def iln(n): return [int(sys.stdin.buffer.readline().rstrip())
                    for _ in range(n)]


def iss(): return sys.stdin.buffer.readline().decode().rstrip()
def sl(): return list(map(str, sys.stdin.buffer.readline().decode().split()))
def isn(n): return [sys.stdin.buffer.readline().decode().rstrip()
                    for _ in range(n)]


def lcm(x, y): return (x * y) // math.gcd(x, y)


# MOD = 10 ** 9 + 7
MOD = 998244353
INF = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    A, B, C = il()
    D = pow(B, C, 4) + 4
    print(pow(A, D, 10))


if __name__ == '__main__':
    main()

考え方

解説AC


累乗を行ったときの1の位は一定の周期でしか変化しません。

累乗 計算結果 1の位
2 ^ 0 1 1
2 ^ 1 2 2
2 ^ 2 4 4
2 ^ 3 8 8
2 ^ 4 16 6
2 ^ 5 32 2
2 ^ 6 64 4
2 ^ 7 128 8
2 ^ 8 256 6
2 ^ 9 512 2

例えば2の累乗であれば2, 4, 8, 6, ...と推移します。(ただし2の0乗は除く)
また、この周期は4回で一周します。
つまり、Aが1乗された1の位と5乗された1の位は同じ値となるため、
(B ^ C) % 4Aの累乗した結果が求めるべき値となります。

Pythonにおいてはpowが繰り返し二乗法で実装されているため、
何も考えずにpowを使用すると簡単に求めることが出来ます。
pow(B, C, 4)の結果がゼロになる場合を考慮する必要がある点に注意。