1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
| // 더 많은 정보는 https://42jerrykim.github.io 에서 확인하세요.
#include <bits/stdc++.h>
using namespace std;
using u128 = unsigned __int128;
using u64 = unsigned long long;
using u32 = unsigned int;
static inline u64 mul_mod(u64 a, u64 b, u64 m) {
return (u128)a * b % m;
}
static inline u64 pow_mod(u64 a, u64 e, u64 m) {
u64 r = 1;
while (e) {
if (e & 1) r = mul_mod(r, a, m);
a = mul_mod(a, a, m);
e >>= 1;
}
return r;
}
static bool is_prime(u64 n) {
if (n < 2) return false;
for (u64 p : {2ull,3ull,5ull,7ull,11ull,13ull,17ull,19ull,23ull,29ull,31ull,37ull}) {
if (n % p == 0) return n == p;
}
u64 d = n - 1, s = 0;
while ((d & 1) == 0) { d >>= 1; ++s; }
// Deterministic bases for 64-bit
for (u64 a : {2ull, 325ull, 9375ull, 28178ull, 450775ull, 9780504ull, 1795265022ull}) {
if (a % n == 0) continue;
u64 x = pow_mod(a % n, d, n);
if (x == 1 || x == n - 1) continue;
bool comp = true;
for (u64 r = 1; r < s; ++r) {
x = mul_mod(x, x, n);
if (x == n - 1) { comp = false; break; }
}
if (comp) return false;
}
return true;
}
static u64 rho(u64 n) {
if ((n & 1ull) == 0) return 2;
std::mt19937_64 rng((u64)chrono::high_resolution_clock::now().time_since_epoch().count());
while (true) {
u64 c = (rng() % (n - 2)) + 1;
u64 x = (rng() % (n - 2)) + 2;
u64 y = x;
u64 d = 1;
auto f = [&](u64 v){ return (mul_mod(v, v, n) + c) % n; };
while (d == 1) {
x = f(x);
y = f(f(y));
u64 diff = x > y ? x - y : y - x;
d = std::gcd(diff, n);
}
if (d != n) return d;
}
}
static void factor(u64 n, vector<u64>& fac) {
if (n == 1) return;
if (is_prime(n)) { fac.push_back(n); return; }
u64 d = rho(n);
factor(d, fac);
factor(n / d, fac);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
unsigned long long n; if (!(cin >> n)) return 0;
if (n == 0) { cout << 0 << '\n'; return 0; }
if (n == 1) { cout << 1 << '\n'; return 0; }
vector<u64> fac; fac.reserve(64);
factor(n, fac);
sort(fac.begin(), fac.end());
fac.erase(unique(fac.begin(), fac.end()), fac.end());
__int128 phi = n;
for (u64 p : fac) {
phi = phi / p * (p - 1);
}
unsigned long long ans = (unsigned long long)phi;
cout << ans << '\n';
return 0;
}
|