結果
| 問題 |
No.8030 ミラー・ラビン素数判定法のテスト
|
| ユーザー |
|
| 提出日時 | 2024-04-03 05:14:02 |
| 言語 | Rust (1.83.0 + proconio) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 1,724 bytes |
| コンパイル時間 | 12,089 ms |
| コンパイル使用メモリ | 393,824 KB |
| 実行使用メモリ | 6,820 KB |
| 最終ジャッジ日時 | 2024-09-30 23:37:55 |
| 合計ジャッジ時間 | 13,593 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 9 WA * 1 |
ソースコード
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() {
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
}