結果

問題 No.2440 Accuracy of Integer Division Approximate Functions
ユーザー 👑 Mizar
提出日時 2023-08-18 06:08:27
言語 JavaScript
(node v23.5.0)
結果
AC  
実行時間 676 ms / 2,000 ms
コード長 1,099 bytes
コンパイル時間 294 ms
コンパイル使用メモリ 7,076 KB
実行使用メモリ 50,060 KB
最終ジャッジ日時 2024-12-23 06:21:28
合計ジャッジ時間 12,464 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 20
権限があれば一括ダウンロードができます

ソースコード

diff #

// calc sum_{i=0}^{n-1} floor((ai + b) / m)
function floor_sum_unsigned(n, m, a, b) {
    let ans = 0n;
    while(true) {
        if (a >= m) {
            ans += (n * (n - 1n) >> 1n) * (a / m);
            a %= m;
        }
        if (b >= m) {
            ans += n * (b / m);
            b %= m;
        }
        let y_max = a * n + b;
        if (y_max < m) {
            return ans;
        }
        [n, b, m, a] = [y_max / m, y_max % m, a, m];
    }
}

function bigint_abs(x) {
    return x < 0n ? -x : x;
}
function bigint_min(...args) {
    return args.reduce((m, e) => e < m ? e : m);
}

function solve(n, d, m, s) {
    let pow2s = 1n << s, dm = d * m;
    if (pow2s != dm) {
        n = bigint_min(n, d * pow2s / bigint_abs(dm - pow2s));
        n -= bigint_abs(floor_sum_unsigned(n + 1n, pow2s, m, 0n) - floor_sum_unsigned(n + 1n, d, 1n, 0n));
    }
    return n;
}

let input = require("fs").readFileSync("/dev/stdin", "utf8").matchAll(/\b(\d+) (\d+) (\d+) (\d+)/g);
for (l of input) {
    [n, d, m, s] = l.slice(1).map(t=>BigInt(t));
    console.log(solve(n, d, m, s).toString());
}
0