HUST 1214 Cubic-free numbers II (容斥原理)

题意:

给出一个范围,求这个范围中满足n=x^3*k的数的个数。

题解:

枚举小于n的素数,然后乱搞(容斥),TL。。。

#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<set>
using namespace std;
#define B(x) (1<<(x))
void cmax(int& a,int b){ if(b>a)a=b; }
void cmin(int& a,int b){ if(b<a)a=b; }
typedef long long ll;
const int oo=0x3f3f3f3f;
const ll OO=1LL<<61;
const int MOD=1000007;
const int maxn=2650000;
ll p[maxn];
int f[maxn];
int dep;
ll res;

void Init(){
    for(int i=2;i<1630;i++){
        if(f[i])continue;
        for(int j=i*i;j<maxn;j+=i){
            f[j]=1;
        }
    }
    int tol=0;
    for(int i=2;i<maxn;i++){
        if(!f[i])p[tol++]=(ll)i*i*i;
    }
}

void dfs(int s,int d,ll x,ll n){
    if(d==dep){
        res+=n/x;
        return;
    }
    for(int i=s;p[i]<=n;i++){
        if(p[i]>n/p[i])break;
        dfs(i+1,d+1,x*p[i],n);
    }

}

ll solve(ll n){
    if(n<=0)return 0;
    ll ans=0;
    for(dep=1;;dep++){
        res=0;
        dfs(0,0,1,n);
        if(dep&1) ans+=res;
        else ans-=res;
        if(!res)break;
    }
    return n-ans;
}

int main(){
    //freopen("E:\\read.txt","r",stdin);
    int T;
    ll a,b;
    Init();
    scanf("%d",&T);
    while(T--){
        scanf("%lld %lld",&a,&b);
        ll ans=solve(b-1)-solve(a-1);
        printf("%lld\n",ans);
    }
    return 0;
}




你可能感兴趣的:(HUST 1214 Cubic-free numbers II (容斥原理))