Skip to content

Commit 98bf4f3

Browse files
authored
handle overflow error on segmented_phi function
Updated the segmented_phi function to handle long long types for larger ranges and adjusted related variables accordingly.
1 parent 6754db9 commit 98bf4f3

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

src/algebra/phi-function.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,9 @@ If we need the totient of all numbers between $L$ and $R$, we can use the [segme
129129
This implementation is based on the divisor sum property, but uses the [segmented sieve](sieve-of-eratosthenes.md#segmented-sieve) approach to compute the totient of all numbers between $L$ and $R$ in $O((R - L + 1) \log \log R)$.
130130
131131
```cpp
132-
const int MAX_RANGE = 1e6 + 6, MAX_R = 1e14;
133-
vector<int> primes;
134-
int phi[MAX_RANGE], rem[MAX_RANGE];
132+
const long long MAX_RANGE = 1e6 + 6, MAX_R = 1e14;
133+
vector<long long> primes;
134+
long long phi[MAX_RANGE], rem[MAX_RANGE];
135135
136136
vector<int> linear_sieve(int n) {
137137
vector<bool> composite(n + 1, 0);
@@ -155,20 +155,20 @@ vector<int> linear_sieve(int n) {
155155
* @note Complexity : O((R - L + 1) * log(log(R)) + sqrt(R))
156156
* @note phi(i) is phi[i - L] where i [L, R]
157157
*/
158-
void segmented_phi(int L, int R) {
159-
for(int i = L; i <= R; i++) {
158+
void segmented_phi(long long L, long long R) {
159+
for(long long i = L; i <= R; i++) {
160160
rem[i - L] = i;
161161
phi[i - L] = i;
162162
}
163163
164-
for(int &i : primes) {
165-
for(int j = max(i * i, (L + i - 1) / i * i); j <= R; j += i) {
164+
for(long long &i : primes) {
165+
for(long long j = max(i * i, (L + i - 1) / i * i); j <= R; j += i) {
166166
phi[j - L] -= phi[j - L] / i;
167167
while(rem[j - L] % i == 0) rem[j - L] /= i;
168168
}
169169
}
170170
171-
for(int i = 0; i < R - L + 1; i++) {
171+
for(long long i = 0; i < R - L + 1; i++) {
172172
if(rem[i] > 1) phi[i] -= phi[i] / rem[i];
173173
}
174174
}

0 commit comments

Comments
 (0)