-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMath.cpp
146 lines (122 loc) · 2.17 KB
/
Math.cpp
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
template<int N>
class Sieve
{
public:
Sieve<N>()
{
init();
}
const vector<int>& getPrimes() const
{
return primes;
}
bool isPrime(int k)
{
assert(0 <= k && k <= N);
return k != 0 && sieve[k] == k;
}
private:
void init()
{
for (int i = 2; i <= N; i++)
{
if (sieve[i] != 0)
continue;
primes.push_back(i);
for (int j = i; j <= N; j += i)
{
sieve[j] = i;
}
}
}
vector<int> primes;
int sieve[N + 1];
};
template<typename T>
class Mapping
{
public:
void init(const vector<T>& raw, int base = 0)
{
start = base;
arr = raw;
sort(arr.begin(), arr.end());
arr.erase(unique(arr.begin(), arr.end()), arr.end());
}
int get_idx(T k)
{
return start + (lower_bound(all(arr), k) - arr.begin());
}
T get_value(int idx)
{
return arr[idx - start];
}
int size()
{
return arr.size();
}
private:
int start = 0;
vector<T> arr;
};
template<int N>
class Factorization
{
public:
Factorization()
{
init();
}
void init()
{
for (int i = 2; i <= N; i++)
{
if (minP[i] != 0)
continue;
for (int j = i; j <= N; j += i)
if (minP[j] == 0)
minP[j] = i;
}
}
// O(logN)
vector<int> seq(int n)
{
vector<int> res;
while (n > 1)
{
res.push_back(minP[n]);
n /= minP[n];
}
return res;
}
// O(logN) (prime, count)
vector<ii> group(int n)
{
vector<ii> res;
while (n > 1)
{
int cnt = 0;
int p = minP[n];
while (n % p == 0)
{
n /= p;
cnt++;
}
res.emplace_back(p, cnt);
}
return res;
}
private:
int minP[N + 5];
};
ii64 gcd_ext(i64 a, i64 b)
{
if (a == 0)
return ii64(0, 1);
if (b == 0)
return ii64(1, 0);
auto [xp, yp] = gcd_ext(b, a % b);
auto x = yp;
auto y = xp - a / b * x;
return ii64(x, y);
}