HDU 4059 The Boss on Mars(容斥原理+四次方数列求和)

题目求1-n中与n互质的数的4次方之和,即S=a1^4+a2^4+……; a1,a2……均小于等于n且与n互质。

基本思路为:先求出1^4+2^4+……n^4然后再减去与n不互质的数的4次方(容斥原理)。

代码如下

#include <bits/stdc++.h>
#define maxn 110000
#define siz 10000
#define mod 1000000007
#define LL long long
using namespace std;

vector<LL>V;
LL t, n;

bool tag[siz];
LL prime[siz];
LL cnt;

void Get_prime()
{
    cnt = 0;
    for(LL i = 2; i < siz; i++){
        if(!tag[i]) prime[cnt++] = i;
        for(LL j = 0; j < cnt && prime[j] * i < siz; j++){
            tag[i * prime[j]] = 1;
            if(i % prime[j] == 0)
                break;
        }
    }
}

LL quick_pow(LL x, LL b){
    LL ans = 1;
    while(b){
        if(b & 1) ans = (ans%mod*x%mod)%mod;
        x = (x%mod*x%mod)%mod;
        b >>= 1;
    }
    return ans;
}

LL Inv(LL x){
    return quick_pow(x, mod-2);
}

LL cal(LL n){
    return (((n%mod*(n+1)%mod)%mod*(6*quick_pow(n,3)%mod+9*quick_pow(n,2)%mod+n-1)%mod)%mod*(Inv(30))%mod)%mod;
}

LL dfs(LL s, bool flag, LL num) {
    LL res = 0;
    LL len = V.size();
    for(LL i = s; i < len; i++) {
        LL t = num * V[i];
        LL p = n/t;
        if(flag) res += (quick_pow(t,4)*cal(p))%mod;
        else res -= (quick_pow(t,4)*cal(p))%mod;
        res %= mod;
        res += dfs(i + 1, !flag, t);
        res %= mod;
    }
    return res%mod;
}

int main()
{
    Get_prime();
    scanf("%lld", &t);
    while(t--){
        V.clear();
        scanf("%lld", &n);
        LL s = n;
        for(LL i=0; i<cnt && s >= prime[i]; i++){
            if(s % prime[i] == 0) V.push_back(prime[i]);
            while(s % prime[i] == 0) s /= prime[i];
        }
        if(s!=1) V.push_back(s);
        LL ans = dfs(0, 1, 1);
        LL res = cal(n);
        cout<<(res - ans + mod)%mod<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值