結果

問題 No.16 累乗の加算
ユーザー Daisuke MiyakawaDaisuke Miyakawa
提出日時 2022-06-18 08:50:59
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 175 ms / 5,000 ms
コード長 1,118 bytes
コンパイル時間 223 ms
コンパイル使用メモリ 82,512 KB
実行使用メモリ 82,944 KB
最終ジャッジ日時 2024-04-18 02:01:34
合計ジャッジ時間 3,243 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 147 ms
82,168 KB
testcase_01 AC 149 ms
82,432 KB
testcase_02 AC 162 ms
82,724 KB
testcase_03 AC 147 ms
82,244 KB
testcase_04 AC 158 ms
82,180 KB
testcase_05 AC 170 ms
82,432 KB
testcase_06 AC 175 ms
82,688 KB
testcase_07 AC 174 ms
82,240 KB
testcase_08 AC 173 ms
82,944 KB
testcase_09 AC 175 ms
82,440 KB
testcase_10 AC 168 ms
82,560 KB
testcase_11 AC 148 ms
82,176 KB
testcase_12 AC 147 ms
82,560 KB
testcase_13 AC 152 ms
82,188 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import math
import unittest


def repeated_squaring_sum(x, A, p):
    """(x^A1 + x^A2 ... + x^An) mod p を求める"""
    a_max = int(math.log2(max(A))) + 1
    cache = [1, x]
    i = 2
    while i <= a_max:
        cache.append((cache[i - 1] ** 2) % p)
        i += 1
    total = 0
    for a in A:
        b = format(a, "b")
        sq = 1
        for i in range(len(b)):
            if b[i] == "1":
                sq = sq * cache[len(b) - i] % p
        total = (total + sq) % p
    return total


class RepeatedSquaringTest(unittest.TestCase):
    def test_1(self):
        MOD = 1_000_003
        self.assertEqual(14, repeated_squaring_sum(2, [1, 2, 3], MOD))
        self.assertEqual(253110, repeated_squaring_sum(2, [0, 100], MOD))


def main():
    import sys
    MOD = 1_000_003
    if len(sys.argv) > 2:
        x = int(sys.argv[1])
        A = [int(e) for e in sys.argv[2:]]
        print(f"x: {x}, A: {A}", file=sys.stderr)
    else:
        x, N = map(int, input().split())
        A = [int(e) for e in input().split()]
    print(repeated_squaring_sum(x, A, MOD))


if __name__ == "__main__":
    main()
0