hdoj-4135-Co-prime

来源:互联网 发布:陈冠希艳照门事件知乎 编辑:程序博客网 时间:2024/06/05 10:48

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.

Sample Input

2
1 10 2
3 15 5

Sample Output

Case #1: 5
Case #2: 10

Hint

In the first test case, the five integers in range [1,10] which are relatively prime to 2 are {1,3,5,7,9}.

这是个简单容斥原理的模板题,数据范围这么大,你暴力跑肯定gg,求[A,B]内与N互质的数,你可以转化成求[1,A-1]与N互质的数,然后求[1,B]内与N互质的数,然后你两个数一减就好了,然后我就套了模板

#include<iostream>#include<cstdio>#include<cstring>#include<vector>using namespace std;typedef long long ll;ll a,b;int n;vector<ll> vt;ll solve(ll x,ll n){    vt.clear();    ll i,j;    for(i=2;i*i<=n;i++)        if(n%i==0){            vt.push_back(i);            while(n%i==0)                n/=i;        }    if(n>1)        vt.push_back(n);    ll sum=0,val,cnt;    for(i=1;i<(1<<vt.size());i++){        val=1;        cnt=0;        for(j=0;j<vt.size();j++)            if(i&(1<<j)){                val*=vt[j];                cnt++;            }        if(cnt&1)            sum+=x/val;        else            sum-=x/val;    }    return x-sum;}int main(){    int t,Cas=1;    scanf("%d",&t);    while(t--){        scanf("%lld%lld%d",&a,&b,&n);        printf("Case #%d: %lld\n",Cas++,solve(b,n)-solve(a-1,n));    }    return 0;}
0 0