数论筛问题

2024-08-14

欧拉素数筛、欧拉函数筛和莫比乌斯函数筛

#include <bits/stdc++.h>
#define io cin.tie(0), cout.tie(0), ios::sync_with_stdio(false)
#define LL long long
#define ULL unsigned long long
#define EPS 1e-8
#define INF 0x7fffffff
#define SUB -INF - 1
using namespace std;
const int N = 105;
int prime[N];
bool vis[N];
int phi[N], mob[N];
int euler_sieve(int n)
{
    int cnt = 0;
    memset(vis, 0, sizeof(vis));
    memset(prime, 0, sizeof(prime));
    for (int i = 2; i <= n; i++)
    {
        if (!vis[i])
            prime[cnt++] = i;
        for (int j = 0; j < cnt; j++)
        {
            if (i * prime[j] > n)
                break;
            vis[i * prime[j]] = 1;
            if (i % prime[j] == 0)
                break;
        }
    }
    return cnt;
}
void get_phi(int n)
{
    phi[1] = 1;
    int cnt = 0;
    for (int i = 2; i < n; i++)
    {
        if (!vis[i])
        {
            vis[i] = i;
            prime[cnt++] = i;
            phi[i] = i - 1;
        }
        for (int j = 0; j < cnt; j++)
        {
            if (i * prime[j] > n)
                break;
            vis[i * prime[j]] = prime[j];
            if (i % prime[j] == 0)
            {
                phi[i * prime[j]] = phi[i] * prime[j];
                break;
            }
            phi[i * prime[j]] = phi[i] * phi[prime[j]];
        }
    }
}
void Mobius_sieve(int n)
{
    int cnt = 0;
    vis[1] = 1;
    mob[1] = 1;
    for (int i = 2; i <= n; i++)
    {
        if (!vis[i])
            prime[cnt++] = i, mob[i] = -1;
        for (int j = 0; j < cnt && 1ll * prime[j] * i <= n; j++)
        {
            vis[i * prime[j]] = 1;
            mob[i * prime[j]] = (i % prime[j]) ? -mob[i] : 0;
            if (i % prime[j] == 0)
                break;
        }
    }
}
int main()
{
    memset(prime, 0, sizeof(prime));
    memset(vis, 0, sizeof(vis));
    int cnt = euler_sieve(N);
    for (int i = 0; i < cnt; i++)
        printf("%d\n", prime[i]);
    memset(prime, 0, sizeof(prime));
    memset(vis, 0, sizeof(vis));
    get_phi(N);
    for (int i = 0; i < N; i++)
        printf("%d\n", phi[i]);
    memset(prime, 0, sizeof(prime));
    memset(vis, 0, sizeof(vis));
    Mobius_sieve(N);
    for (int i = 0; i < N; i++)
        printf("%d\n", mob[i]);
    return 0;
}