提高+省选-专题[数论][容斥]:SP12660 LCPC11B - Co-Prime

· · 题解

我这里推荐一下我的博客

在博客里观看更美观哦~

题目

华丽的分割线

解析

问题转化

求[a,b]区间内与n互素的个数可转化为[1,b]的个数-[1,a-1]的个数

问题转化为求[1,m]区间内与n互素的个数,根据容斥原理,可转化为

m-[1,m]区间内不与n互素的个数

O(sqrt(n))分解质因数

因为>sqrt(n)的质因数至多只有一个(有两个相乘则>n)

i从2到sqrt(n)枚举,若n%i==0,则不断n/=i直到n%i!=0

也就是说遇到一个i则将n中所有含i的因子除尽,则i及下一个i都是n的质因子

最后除完的n若不等于1,则n为原来n中>sqrt(n)的一个质因子

容斥原理

把n分解质因数,个数不超过logn个,则[1,m]中含有n的质因数的数与n不互素

假设n有三个质因数2,3,5,则[1,m]中2的倍数的个数为m/2(向下取整)

同理3的倍数个数为m/3,但对于6来说,它既是2的倍数,也是3的倍数,被删了两次

6的倍数都被删了两次,所以再加上m/6

同理-m/5 +m/10 +m/15但30的倍数+三次-三次没有删去,所以-m/30

也就是说对于质因数乘积的组合,奇数个相减,偶数个相加

用搜索实现组合型枚举即可

则解决了[1,m]中与n互素个数问题,也就解决了[a,b]区间内与n互素的个数

代码

#include<cstdio>
#include<cmath>
#define ll long long 
using namespace std;
ll a[10001];
int atot,n;
ll ans,div;
bool f;
bool book[10001];
void read(int &x)
{
    x=0;
    int f;
    f=1;
    char c;
    c=getchar();
    while((c<'0'||c>'9')&&c!='-')
    {
        c=getchar();
    }
    if(c=='-')
    {
        f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9')
    {
        x=(x<<3)+(x<<1)+(c^48);
        c=getchar();
    }
    x=x*f;
}
void read(ll &x)
{
    x=0;
    ll f;
    f=1;
    char c;
    c=getchar();
    while((c<'0'||c>'9')&&c!='-')
    {
        c=getchar();
    }
    if(c=='-')
    {
        f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9')
    {
        x=(x<<3)+(x<<1)+(c^48);
        c=getchar();
    }
    x=x*f;
} 
void dfs(int x,int sum,ll no)
{
    if(sum==0)
    {
        if(f==1)
        {
            ans+=no/div;
        }
        else
        {
            ans-=no/div;
        }
        return;
    }
    int i;
    for(i=x;i<=n;i++)
    {
        if(book[i]==0)
        {
            book[i]=1;
            div*=a[i];
            dfs(i,sum-1,no);
            div/=a[i];
            book[i]=0;
        }
    }
}
ll Q(ll x)
{
    ans=x;
    int i,j;
    for(i=1;i<=atot;i++)
    {
        ans-=x/a[i];
        for(j=1;j<i;j++)
        {
            n=i-1;
            div=a[i];
            if(j%2==1)
            {
                f=1;
            }
            else
            {
                f=0;
            }
            dfs(1,j,x);
        }  
    }
    return ans;
}
int main()
{
    int t,ti;
    ll n,i,A,B,up;
    read(t);
    for(ti=1;ti<=t;ti++)
    {
        read(A);
        read(B);
        read(n);
        up=sqrt(n);
        atot=0;
        for(i=2;i<=up;i++)
        {
            if(n%i==0)
            {
                atot++;
                a[atot]=i;
            }
            while(n%i==0)
            {
                n/=i;
            }
        }
        if(n!=1)
        {
            atot++;
            a[atot]=n;
        }
        printf("Case #%d: %lld\n",ti,Q(B)-Q(A-1));
    }
}