1. 程式人生 > >HDU 5608(杜教篩)

HDU 5608(杜教篩)

problem

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

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

calulate ∑Ni=1f(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

T≤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)=01^2-3*1+2=f(1)=0 2232+2=f(2)+f(1)=0>f(2)=02^2-3*2+2=f(2)+f(1)=0->f(2)=0 3233+2=f(3)+f(1)=2>f(3)=23^2-3*3+2=f(3)+f(1)=2->f(3)=2

f(1)+f(2)+f(3)=2f(1)+f(2)+f(3)=2

思路

題目相當於直接給了卷積的形式,於是變成杜教篩的裸題 注意先預處理出部分字首和函式的值

    for(int i=1;i<=n;++i){
        f[i]=(f[i]+(1LL*i*i-3*i+2));
        for(int j=2*i;j<=n;j+=i){
            f[j]=(f[j]-f[i]);
        }
    }

總時間複雜度O(n23logn+Tn23)

O(n^{\frac{2}{3}}logn+T*n^{\frac{2}{3}})

程式碼示例

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const int mod=1e9+7;
const int maxn=1e6+10;
const int ni6=166666668;
const int ni2=500000004;
int up,ni3;

ll f[maxn];

ll fast_exp(ll a,ll b,ll c)
{
    ll res=1;
    while(b)
    {
        if(b&1){
            res=res*a%c;
        }
        a=a*a%c;
        b>>=1;
    }
    return res;
}

void init(int n)
{
    for(int i=1;i<=n;++i){
        f[i]=(f[i]+(1LL*i*i-3*i+2));
        for(int j=2*i;j<=n;j+=i){
            f[j]=(f[j]-f[i]);
        }
    }
    for(int i=1;i<=n;++i) {
        f[i]=(f[i-1]+f[i])%mod;
    }
//    f[1]=0;
//    help_sum[1]=0;
//    for(int i=2;i<=n;++i){
//        f[i]=(f[i-1]+2LL*i-4)%mod;
//        help_sum[i]=(help_sum[i-1]+f[i])%mod;
//    }
}

unordered_map<ll,int> mp;
set<ll> st;

ll solve(ll n)
{
    if(n<=up) return f[n];
    if(st.count(n)) return mp[n];
    st.insert(n);
    int &res = mp[n];
    for(ll l=2,r;l<=n;l=r+1){
        r=n/(n/l);
        res=(res-(r-l+1)%mod*solve(n/l)%mod)%mod;
    }
    n%=mod;
    ll tp=n*n%mod;
    return res=(res+(tp*n%mod-3*tp%mod+2*n)%mod*ni3)%mod;
}

int main()
{
    ni3=fast_exp(3,mod-2,mod);
    ios::sync_with_stdio(false);
    int t;
    up=1e6;
    init(up);
    //cout<<f[1000000]<<endl;
    //cout<<clock()<<endl;
    //cout<<f[1]+f[2]+f[3]<<endl;
    cin>>t;
    while(t--)
    {
        ll n;
        cin>>n;
        cout<<(solve(n)%mod+mod)%mod<<endl;
    }
    return 0;
}