【hdu4135】Co-prime(容斥原理)

Problem Description

Given a number N, you are asked to count the number of integers between A and B inclusive which are relatively prime to N.
Two integers are said to be co-prime or relatively prime if they have no common positive divisors other than 1 or, equivalently, if their greatest common divisor is 1. The number 1 is relatively prime to every integer.

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 <= 10^15) and (1 <=N <= 10^9).

Output

For each test case, print the number of integers between A and B inclusive which are relatively prime to N. Follow the output format below.

题解:

在A到B间,与N互素的数的个数。
范围很大,暴力超时,打表超数组范围。所以我们要换一个思路,先找到N的质因子,然后在1~B找到能整数N质因子的数的个数,在从1~A找,然后相减再加1。
找能够整除N的质因子可用容斥原理。
不懂容斥原理的点这里(^_^)

代码:

#include<iostream>
#include<stdio.h>
using namespace std;
typedef long long LL;
int m[1000];
LL a,b,n,k;
LL gcd(LL x,LL y)
{
    if(y==0) return x;
    else return gcd(y,x%y);
}
void init()  //N的质因子打表
{
    for(LL i=2;i*i<=n;i++)
    {
        if(n%i==0)
        {
            m[k++]=i;
            while(n%i==0)
                n/=i;
        }
    }
    if(n>1)
        m[k++]=n;
}
LL slove(LL N)   //整除N的质因子的个数
{
  LL res=0;
  for(LL i=1;i<(1<<k);i++)
  {
      LL num=0;
      for(LL j=i;j!=0;j>>=1) num+=j&1;
      LL lcm=1;
      for(LL j=0;j<k;j++)
      {
          if(i>>j&1)
          {
              lcm=lcm/gcd(lcm,m[j])*m[j];
              if(lcm>N) break;
          }
      }
      if(num%2==0) res-=N/lcm;
      else res+=N/lcm;
  }
  return res;
}
int main()
{
    int t;
    scanf("%d",&t);
    int cns=1;
    while(t--)
    {
        k=0;
        scanf("%lld%lld%lld",&a,&b,&n);
        init();
        LL res=slove(b)-slove(a-1);
        printf("Case #%d: %lld\n",cns++,b-a-res+1);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lhhnb/article/details/80368709