cplusplusonly's memo

Atcoder: https://atcoder.jp/users/cplusplusonly

REP マクロの罠

本日の ABC 179 E の愚直解

#include <iostream>
#include <vector>
#include <cinttypes>

#define REP(n) for (int repeat_index = 0; repeat_index < (int)n; repeat_index++)

using namespace std;

int main()
{
    int64_t n, x, m;
    cin >> n >> x >> m;

    int64_t sum = 0;
    REP(n) {
        sum += x;
        x = x * x % m;
    }
    cout << sum << endl;

    return 0;
}

は TLE ではなく WA となります。実行結果

愚直に計算しているだけなのになぜ合わない?となったのですが、実は REP マクロの中の n との比較に int へのキャストが入っているため、1.0E10 が上限の n に対してはリピート回数は n とは限らないのでした...。int へのキャスト自体は別の問題で型不整合により間違いを引き起こしたために入れておいたのですがこれが裏目に出たようです。

REP マクロは以下のように decltype で型をあわせるのがよさそうです。

#define REP(n) for (decltype(n) repeat_index = 0; repeat_index < (int)n; repeat_index++)