Skip to content

Commit ce40f15

Browse files
committed
Primitive root test
1 parent 84d2b11 commit ce40f15

File tree

3 files changed

+51
-4
lines changed

3 files changed

+51
-4
lines changed

cp-algo/algebra/modint.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ namespace cp_algo::algebra {
8585
using Base::Base;
8686

8787
// Wrapper for temp switching
88-
auto static with_switched_mod(int64_t tmp, auto callback) {
88+
auto static with_mod(int64_t tmp, auto callback) {
8989
auto prev = mod();
9090
switch_mod(tmp);
9191
if constexpr(std::is_void_v<std::invoke_result_t<decltype(callback)>>) {

cp-algo/algebra/number_theory.hpp

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ namespace cp_algo::algebra {
4848
}
4949
return x == -1;
5050
};
51-
return base::with_switched_mod(m, [&](){
51+
return base::with_mod(m, [&](){
5252
// Works for all m < 2^64: https://miller-rabin.appspot.com
5353
return std::ranges::all_of(std::array{
5454
2, 325, 9375, 28178, 450775, 9780504, 1795265022
@@ -64,7 +64,7 @@ namespace cp_algo::algebra {
6464
res.push_back(m);
6565
} else if(m > 1) {
6666
using base = dynamic_modint;
67-
base::with_switched_mod(m, [&]() {
67+
base::with_mod(m, [&]() {
6868
base t = random::rng();
6969
auto f = [&](auto x) {
7070
return x * x + t;
@@ -90,10 +90,29 @@ namespace cp_algo::algebra {
9090
});
9191
}
9292
}
93-
auto factorize(int64_t m) {
93+
std::vector<int64_t> factorize(int64_t m) {
9494
std::vector<int64_t> res;
9595
factorize(m, res);
9696
return res;
9797
}
98+
int64_t primitive_root(int64_t p) {
99+
using base = dynamic_modint;
100+
return base::with_mod(p, [p](){
101+
auto fact = factorize(p - 1);
102+
auto is_primitive_root = [&](base x) {
103+
for(auto t: fact) {
104+
if(bpow(x, (p - 1) / t) == 1) {
105+
return false;
106+
}
107+
}
108+
return true;
109+
};
110+
base t = 1;
111+
while(!is_primitive_root(t)) {
112+
t = random::rng();
113+
}
114+
return t.getr();
115+
});
116+
}
98117
}
99118
#endif // CP_ALGO_ALGEBRA_NUMBER_THEORY_HPP
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// @brief Primitive Root
2+
#define PROBLEM "https://judge.yosupo.jp/problem/primitive_root"
3+
#pragma GCC optimize("Ofast,unroll-loops")
4+
#pragma GCC target("avx2,tune=native")
5+
#include "cp-algo/algebra/number_theory.hpp"
6+
#include <bits/stdc++.h>
7+
8+
using namespace std;
9+
using namespace cp_algo;
10+
using namespace algebra;
11+
using base = dynamic_modint;
12+
13+
void solve() {
14+
int64_t p;
15+
cin >> p;
16+
cout << primitive_root(p) << "\n";
17+
}
18+
19+
signed main() {
20+
//freopen("input.txt", "r", stdin);
21+
ios::sync_with_stdio(0);
22+
cin.tie(0);
23+
int t = 1;
24+
cin >> t;
25+
while(t--) {
26+
solve();
27+
}
28+
}

0 commit comments

Comments
 (0)