結果
| 問題 |
No.8030 ミラー・ラビン素数判定法のテスト
|
| ユーザー |
|
| 提出日時 | 2022-06-11 18:05:55 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 381 ms / 9,973 ms |
| コード長 | 1,374 bytes |
| コンパイル時間 | 1,891 ms |
| コンパイル使用メモリ | 194,020 KB |
| 最終ジャッジ日時 | 2025-01-29 20:38:18 |
|
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 10 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
using ll = int64_t;
using ull = uint64_t;
using ld = long double;
constexpr ll MOD = 1e9 + 7;
constexpr ll INF = 1e+18;
constexpr ld EPS = 1e-12L;
constexpr ld PI = 3.14159265358979323846L;
// Miller test for 64bit
// https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
bool isPrime(ull n) {
if(n == 2) {
return true;
}
if(!(n & 1) || n == 1) {
return false;
}
auto powmod64 = [](ull x, ull y, ull mod) -> ull {
ull ret = 1;
while(y) {
if(y & 1) {
ret = (__uint128_t)ret * x % mod;
}
x = (__uint128_t)x * x % mod;
y >>= 1;
}
return ret;
};
const ull primes[12] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};
int r = 0;
ull d = n - 1;
while(!(d & 1)) {
d >>= 1;
++r;
}
for(const ull p: primes) {
if(p > n - 2) {
break;
}
ull x = powmod64(p, d, n);
if(x == 1 || x == n - 1) {
continue;
}
bool composite = true;
for(int i = 0; i < r - 1; ++i) {
x = powmod64(x, 2, n);
if(x == n - 1) {
composite = false;
break;
}
}
if(composite) {
return false;
}
}
return true;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n;
cin >> n;
while(n--) {
ull x;
cin >> x;
cout << x << ' ' << isPrime(x) << '\n';
}
}