結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー 👑 MizarMizar
提出日時 2022-08-31 18:58:29
言語 Rust
(1.77.0)
結果
AC  
実行時間 202 ms / 9,973 ms
コード長 1,547 bytes
コンパイル時間 11,144 ms
コンパイル使用メモリ 377,872 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-28 10:03:52
合計ジャッジ時間 12,474 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 0 ms
5,248 KB
testcase_01 AC 1 ms
5,376 KB
testcase_02 AC 1 ms
5,376 KB
testcase_03 AC 1 ms
5,376 KB
testcase_04 AC 112 ms
5,376 KB
testcase_05 AC 108 ms
5,376 KB
testcase_06 AC 44 ms
5,376 KB
testcase_07 AC 43 ms
5,376 KB
testcase_08 AC 45 ms
5,376 KB
testcase_09 AC 202 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

// -*- coding:utf-8-unix -*-

pub fn modmul(a: u64, b: u64, n: u64) -> u64 { ((a as u128) * (b as u128) % (n as u128)) as u64 }
pub fn modpow(mut b: u64, mut p: u64, n: u64) -> u64 {
    let mut r = if (p & 1) == 0 { 1 } else { b };
    loop {
        p >>= 1; if p == 0 { return r; }
        b = modmul(b, b, n); if p & 1 != 0 { r = modmul(r, b, n) }
    }
}
pub fn miller_rabin(n: u64) -> bool {
    if n == 2 { return true; }
    if n < 2 || n & 1 == 0 { return false; }
    let n1 = n - 1;
    let s = n1.trailing_zeros();
    let d = n1 >> s;
    [2,325,9375,28178,450775,9780504,1795265022].iter().all(|&base| {
        let a = if base < n { base } else { base % n };
        if a == 0 { return true; }
        let mut t = modpow(a, d, n);
        if t == 1 || t == n1 { return true; }
        for _ in 1..s { t = modmul(t, t, n); if t == n1 { return true; } }
        false
    })
}

fn main() {
    use std::io::{BufRead,Write};
    let start_time = std::time::Instant::now();
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());
    macro_rules! puts {($($format:tt)*) => (let _ = write!(out,$($format)*););}
    let input = std::io::stdin();
    let mut lines = std::io::BufReader::new(input.lock()).lines();
    let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..n {
        let x: u64 = lines.next().unwrap().unwrap().parse().unwrap();
        puts!("{} {}\n", x, if miller_rabin(x) { "1" } else { "0" });
    }
    eprint!("{}us\n", start_time.elapsed().as_micros());
}
0