今天看了一天数论,学了埃式筛和欧拉筛,还有欧拉函数。
欧拉函数
就是找到从1~n与n互质的数的个数。
这个就是一个公式,然后根据容斥定理进行推导
φ(n)=n*(1-1/p1)(1-1/p2)(1-1/p3)*(1-1/p4)……(1-1/pn)
//欧拉函数
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
while (n--) {
int a;
cin >> a;
int res = a;
for (int i = 2; i <= a / i; i++) {
if (a % i == 0) {
res = res / i * (i - 1);
while (a % i == 0)
a /= i;
}
}
if (a > 1) {
res = res / a * (a - 1);
}
printf("%d\n", res);
}
return 0;
}
埃式筛
//埃式筛
#include<iostream>
using namespace std;
const int N = 1e6 + 10;
int prime[N],primes[N], cnt,s;
bool vis[N],st[N];
//只有是质数时才会删掉数
void divide(int n) {
for (int i = 2; i <= n; i++) {
if (!vis[i]) {
prime[cnt++] = n;
for (int j = i + i; j <= n; j += i)
vis[j] = true;
}
}
printf("%d\n", cnt);
}
//从2-->n的每个数都要进行筛
void di(int n) {
for (int i = 2; i <= n; i++) {
if (!st[i]) {
primes[s++] = n;
}
for (int j = i + i; j <= n; j += i) {
st[N] = true;
}
}
}
int main() {
int n;
scanf("%d", &n);
divide(n);
return 0;
}
欧拉筛
//线性筛(每一个数都会被它的最小质因子筛掉)
#include<iostream>
using namespace std;
const int N = 1e6 + 10;
int prime[N], cnt;
bool st[N];
void divide(int n) {
for (int i = 2; i <= n; i++) {
if (!st[i]) prime[cnt++] = i;
for (int j = 0; prime[j] <= n / i; j++) {
st[prime[j] * i] = true;
if (i%prime[j] == 0)break; //prime[j]一定是i的最小质因子
}
}
}
int main() {
int n;
scanf("%d", &n);
divide(n);
printf("%d\n", cnt);
return 0;
}