結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー pogyomopogyomo
提出日時 2024-04-03 05:24:24
言語 Rust
(1.77.0)
結果
AC  
実行時間 247 ms / 9,973 ms
コード長 1,766 bytes
コンパイル時間 561 ms
コンパイル使用メモリ 180,488 KB
実行使用メモリ 6,676 KB
最終ジャッジ日時 2024-04-03 05:24:26
合計ジャッジ時間 1,887 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
6,676 KB
testcase_01 AC 1 ms
6,676 KB
testcase_02 AC 1 ms
6,676 KB
testcase_03 AC 1 ms
6,676 KB
testcase_04 AC 144 ms
6,676 KB
testcase_05 AC 139 ms
6,676 KB
testcase_06 AC 64 ms
6,676 KB
testcase_07 AC 63 ms
6,676 KB
testcase_08 AC 63 ms
6,676 KB
testcase_09 AC 247 ms
6,676 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

use std::iter::successors;

fn main() {
    let mut lines = std::io::stdin().lines();
    let n = {
        let line = lines.next().unwrap().unwrap();
        line.trim().parse::<usize>().unwrap()
    };
    for _ in 0..n {
        let line = lines.next().unwrap().unwrap();
        let x = line.trim().parse::<u64>().unwrap();
        if fast_is_prime(x) {
            println!("{x} 1");
        } else {
            println!("{x} 0");
        }
    }
}

fn pow_mod(x: u128, mut n: u128, p: u128) -> u128 {
    let mut a = x % p;
    let mut res = 1;
    while n != 0 {
        if n & 1 != 0 {
            res = (res * a) % p;
        }
        a = (a * a) % p;
        n >>= 1;
    }
    res
}

/// Check if the given integer is prime or not based on Miller-Rabin primality test.
/// Time complexity is O(logn)
pub fn fast_is_prime(n: u64) -> bool {
    // reference:
    // * https://miller-rabin.appspot.com
    // * https://drken1215.hatenablog.com/entry/2023/05/23/233000
    const A: [u64; 7] = [2, 325, 9375, 28178, 450775, 9780504, 1795265022];

    match n {
        0 | 1 => return false,
        2 => return true,
        n if n & 1 == 0 => return false,
        _ => (),
    }

    let (s, d) = {
        let mut n = n - 1;
        let mut s = 0;
        while n & 1 == 0 {
            s += 1;
            n >>= 1;
        }
        (s, n)
    };
    for a in A.into_iter().map(|a| a % n).take_while(|a| a % n != 0) {
        let x = pow_mod(a as u128, d as u128, n as u128) as u64;
        if x != 1 {
            let xs = successors(Some(x), |&x| {
                Some(((x as u128 * x as u128) % n as u128) as u64)
            });
            if xs.take(s).all(|x| x != n - 1) {
                return false;
            }
        }
    }
    true
}
0