杜教筛模板

文章详细介绍了如何使用C++编写代码来计算给定整数n的欧拉函数φ(n)和莫比乌斯函数μ(n),通过循环和模板实现高效求解,适用于数学和IT技术相关问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<unordered_map>
using namespace std;
#define  LL long long 
const int N = 2e6 + 10;
const long long mod = 998244353;
const double PI = acos(-1);
LL su[N], a[N], mu[N], phi[N], cn;
LL n;
map<LL, LL> mpu, mpp;
void init()
{
     a[0] = a[1] = mu[1] = phi[1] = 1;
     for (int i = 2; i < N; i++)
     {
         if (!a[i]) su[++cn] = i, mu[i] = -1, phi[i] = i - 1;
         for (int j = 1; j <= cn&&(LL)i*su[j]<N; j++)
         {
             int pm = su[j];
             a[pm * i] = 1;
             if (i % pm == 0)
             {
                 phi[i * pm] = phi[i] * pm;
                 break;
             }
             mu[i * pm] = -1 * mu[i];
             phi[i * pm] = phi[i] * (pm - 1);
         }
      }
     for (int i = 1; i < N; i++)
         mu[i] += mu[i - 1], phi[i] += phi[i - 1];
}
LL seekphi(LL n)
{
    if (n < N) return phi[n];
    if (mpp[n]) return mpp[n];
    LL ans = n * (n + 1) / 2;
    for (LL l = 2, r; l <= n; l = r + 1)
    {
        if (n / l == 0) r = n;
        else
        r = min(n / (n / l),n);
        ans -= (r - l + 1) * seekphi(n / l);
    }
    mpp[n] = ans;  
    return ans;
}
LL seekmu(LL n)
{
    if (n < N) return mu[n];
    if (mpu[n]) return mpu[n];
    LL ans = 1;
    for (LL l = 2, r; l <= n; l = r + 1)
    {
        if (n / l == 0) r = n;
        else
        r = min(n / (n / l), n);
        ans -= (r - l + 1) * seekmu(n / l);
    }
    mpu[n] = ans;
    return ans;
}
int main() {
    init();
    int T;
    cin >> T;
    while (T--)
    {
        cin >> n;
        LL ans1 =seekphi(n),ans2=seekmu(n);
        cout << ans1 <<" "<<ans2<< endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值