1. 程式人生 > >hdu 4135 a到b的範圍中多少數與n互質(容斥)

hdu 4135 a到b的範圍中多少數與n互質(容斥)

namespace rim 所有 += ont put contain 質因數 tor

Co-prime

題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=4135

input

The first line on input contains T (0 < T <= 100) the number of test cases,

each of the next T lines contains three integers A, B, N where (1 <= A <= B <= 1015) and (1 <=N <= 109).

題解:先求出n的所有質因數,因為n最大為1e9所以最多10個

利用二進制來模擬是否乘上某個質因數,例如有個n為2*3*5=30

1-x中共有ans個數與其互質 ans=-x/2-x/3-x/5+x/6+x/10+x/15-x/30

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
long long fa[20];
long long factor(long long x)
{
    long long num=0;
    for(long long i=2;i*i<=x;i++)
    {
         if(x%i==0)
         {
             fa[num++]=i;
             while(x%i==0)x/=i;
         }
    }
    if(x>1)fa[num++]=x;
    return num;
}
long long un(long long  x,long long num)
{
    long long res=0;
    for(long long i=0;i<(1<<num);i++)
    {
        long long g=1,k=0;
        for(long long j=0;j<num;j++)
        {
            if(i&(1<<j))
              g*=fa[j],k++;
        }
        if(k%2)
            res-=x/g;
        else
            res+=x/g;
    }
    return res;
}
int main()
{
    long long T,n,i=1;
    long long a,b,ans;
    scanf("%I64d",&T);
    while(T--)
    {
        scanf("%I64d %I64d %I64d",&a,&b,&n);
        long long num=factor(n);
        ans=un(b,num)-un(a-1,num);
        printf("Case #%I64d: ",i++);
        printf("%I64d\n",ans);
    }
	return 0;
}

  

hdu 4135 a到b的範圍中多少數與n互質(容斥)