【HDU 5608】function(杜教筛)

本文介绍了一种基于数论的优化求和算法,通过预处理和递归集约化方式加速计算过程。针对特定数学方程,实现了高效计算并解决大规模数据集的问题。

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

Problem Description
There is a function f(x),which is defined on the natural numbers set N,satisfies the following eqaution

N23N+2=d|Nf(d)N2−3N+2=∑d|Nf(d)

calulate ni=1f(i) mod 109+7∑i=1nf(i) mod 109+7.

Input
the first line contains a positive integer T,means the number of the test cases.

next T lines there is a number N

T500,N109T≤500,N≤109

only 5 test cases has N>106.

Output
Tlines,each line contains a number,means the answer to the i-th test case.

Sample Input
1
3

Sample Output
2

1231+2=f(1)=012−3∗1+2=f(1)=0
2232+2=f(2)+f(1)=0>f(2)=022−3∗2+2=f(2)+f(1)=0−>f(2)=0
3233+2=f(3)+f(1)=2>f(3)=232−3∗3+2=f(3)+f(1)=2−>f(3)=2
f(1)+f(2)+f(3)=2f(1)+f(2)+f(3)=2

先前的写法是纯记忆化,但是超时了啊。所以果然还是像杜教筛一样先预处理前1000000的ans,然后在递归集约化搞就是了。
代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<algorithm>
#include<cmath>
#define maxx 1000005
#define ll long long
using namespace std;
const int mod=1000000007;
ll ans[maxx];
map<ll ,ll> M;
ll inv=333333336;
void init()
{
    for(int i=1;i<maxx;i++) ans[i]=((ll)i-1)*(i-2)%mod;
    for(int i=1;i<maxx;i++)
        for(int j=i+i;j<maxx;j+=i)
            ans[j]=(ans[j]-ans[i]+mod)%mod;
    for(int i=1;i<maxx;i++)
        ans[i]=(ans[i]+ans[i-1])%mod;
}
ll work(ll x)
{
    if(x<maxx)  return ans[x];
    if(M[x])return M[x];
    ll res=x*(x-1)%mod*(x-2)%mod*inv%mod;
    for(ll i=2,last;i<=x;i=last+1)
    {
        last=x/(x/i);
        res=(res-(last-i+1)*work(x/i)%mod)%mod;
    }
    res=(res+mod)%mod;
    M[x]=res;
    return res;
}
ll p(ll a,ll b)
{
    ll ans=1;
    while(b)
    {
        if(b&1)ans=ans*a%mod;
        a=a*a%mod;
        b>>=1;
    }
    return ans;
}
int main()
{
    //cout<<p(3,mod-2)<<endl;
    init();
    ans[1]=0;
    int t;
    cin>>t;
    while(t--)
    {
        ll n;
        scanf("%lld",&n);
        printf("%lld\n",work(n));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值