結果

問題 No.1092 modular arithmetic
ユーザー tenten
提出日時 2020-12-29 08:56:11
言語 Java
(openjdk 23)
結果
AC  
実行時間 666 ms / 2,000 ms
コード長 1,079 bytes
コンパイル時間 2,115 ms
コンパイル使用メモリ 77,012 KB
実行使用メモリ 52,084 KB
最終ジャッジ日時 2024-10-05 00:40:51
合計ジャッジ時間 19,197 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 32
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
    static int MOD;
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        MOD = sc.nextInt();
        int n = sc.nextInt();
        int[] nums = new int[n];
        for (int i = 0; i < n; i++) {
            nums[i] = sc.nextInt();
        }
        char[] ops = sc.next().toCharArray();
        long ans = nums[0];
        for (int i = 1; i < n; i++) {
            if (ops[i - 1] == '+') {
                ans += nums[i];
            } else if (ops[i - 1] == '-') {
                ans += -nums[i] + MOD;
            } else if (ops[i - 1] == '*') {
                ans *= nums[i];
            } else {
                ans *= pow(nums[i], MOD - 2);
            }
            ans %= MOD;
        }
        System.out.println(ans);
    }
    
    static long pow(long x, int p) {
        if (p == 0) {
            return 1;
        } else if (p % 2 == 0) {
            return pow(x * x % MOD, p / 2);
        } else {
            return pow(x, p - 1) * x % MOD;
        }
    }
}
0