-
Notifications
You must be signed in to change notification settings - Fork 2
/
Sieve.cpp
144 lines (126 loc) · 2.49 KB
/
Sieve.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
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define si(x) scanf("%d", &x)
#define sc(x) scanf("%c", &x)
#define sl(x) scanf("%lld", &x)
#define pl(x) printf("%lld\n", x)
#define pi(x) printf("%d\n", x)
#define setbits __builtin_popcountll
#define MOD 1000000007
#define speed ios::sync_with_stdio(false)
const int N = 100005;
int prime[N];
ll divisors[N];
ll sod[N];
ll lprime[N];
ll hprime[N];
vector <ll> pf;
vector <int> pr;
// STANDARD SIEVE
void sieve(int N){
int i, j;
memset(prime, 0, sizeof(prime));
prime[0] = 1; prime[1] = 1;
for(i = 2; i * i <= N; i++){
if(prime[i] == 0){
for(j = i * i; j <= N; j += i){
prime[j] = 1;
}
}
}
for(i = 2; i <= N; i++){
if(prime[i] == 0){
pr.push_back(i);
}
}
}
// NUMBER OF DIVISORS USING SIEVE
void sieve(int N){
int i, j;
memset(divisors, 0, sizeof(divisors));
for(i = 1; i <= N; i++){
for(j = i; j <= N; j += i){
divisors[j]++;
}
}
}
// SUM (OR PRODUCT) OF DIVISORS USING SIEVE
void sieve(int N){
int i, j;
memset(sod, 0, sizeof(sod));
for(i = 1; i <= N; i++){
for(j = i; j <= N; j += i){
sod[j] += i; // ( USE * FOR PRODUCT OF DIVISORS )
}
}
}
// LOWEST PRIME FACTOR USING SIEVE
void sieve(int N){
ll i, j;
memset(lprime, 0, sizeof(lprime));
lprime[1] = 0;
for(i = 2; i <= N; i++){
if(lprime[i] == 0){
lprime[i] = i;
for(j = i * i; j <= N; j += i){
if(lprime[j] == 0){
lprime[j] = i;
}
}
}
}
}
// HIGHEST PRIME FACTOR USING SIEVE AND PRIME FACTORIZATION
void sieve(int N){
int i, j;
memset(hprime, 0, sizeof(hprime));
hprime[1] = 0;
for(i = 2; i <= N; i++){
if(hprime[i] == 0){
for(j = i; j <= N; j += i){
hprime[j] = i;
}
}
}
}
void pfactor(int a){
pf.clear();
while(a > 1){
pf.push_back(hprime[a]);
a /= hprime[a];
}
}
// LINEAR RUNTIME SIEVE - LOWEST PRIME IN O(n)
void sieve1(int N){
int i, j;
memset(lprime, 0, sizeof(lprime));
for(i = 2; i <= N; i++){
if(lprime[i] == 0){
lprime[i] = i;
pr.push_back(i);
}
for(j = 0; j < pr.size() && pr[j] <= lprime[i] && i * pr[j] <= N; j++){
lprime[i * pr[j]] = pr[j];
}
}
}
// SEGMENTED SIEVE - ( HIGH - LOW <= 10^6 )
void segSieve(int low, int high){
int i, j;
memset(segPrime, 0, sizeof(segPrime));
for(i = 0; i < pr.size() && pr[i] * pr[i] <= high; i++){
int L = floor(low / pr[i]) * pr[i];
if(L < low){
L += pr[i];
}
for(j = L; j <= high; j += pr[i]){
if(pr[i] != j){
segPrime[j - low] = 1;
}
}
if(low == 1){
segPrime[0] = 1;
}
}
}