maomao90's Library
A C++20 library for competitive programming.
Loading...
Searching...
No Matches
primality_test.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <concepts>
4
7
8namespace maomao90 {
9using namespace std;
10template <unsigned_integral T>
11 requires internal::type_traits::is_64bit_or_less_v<T>
12constexpr bool miller_rabin(const T &n, const T *bases, const size_t size) {
13 using U = internal::type_traits::safely_multipliable_t<T>;
14 if (n <= 1) {
15 return false;
16 }
17 if (n == 2) {
18 return true;
19 }
20 if (n % 2 == 0) {
21 return false;
22 }
23 T d = n - 1;
24 while (d % 2 == 0)
25 d /= 2;
26 for (size_t i = 0; i < size; i++) {
27 T a = bases[i];
28 if (a % n == 0) {
29 continue;
30 }
31 T t = d, y = pow_mod<T, T>(a, t, n);
32 while (t != n - 1 && y != 1 && y != n - 1) {
33 y = (U)y * y % n;
34 t <<= 1;
35 }
36 if (y != n - 1 && t % 2 == 0) {
37 return false;
38 }
39 }
40 return true;
41}
42template <unsigned_integral T>
43 requires internal::type_traits::is_64bit_or_less_v<T>
44constexpr bool is_prime(T n) {
45 if constexpr (internal::type_traits::is_32bit_or_less_v<T>) {
46 T bases[3] = {2, 7, 61};
47 return miller_rabin<T>(n, bases, 3);
48 } else {
49 T bases[7] = {2, 325, 9375, 28178, 450775, 9780504, 1795265022};
50 return miller_rabin<T>(n, bases, 7);
51 }
52}
53} // namespace maomao90
Definition hashmap.hpp:8
constexpr T pow_mod(T b, P p, T mod)
Definition pow_mod.hpp:12
constexpr bool miller_rabin(const T &n, const T *bases, const size_t size)
Definition primality_test.hpp:12
constexpr bool is_prime(T n)
Definition primality_test.hpp:44