HDU 4135解題報告

Co-prime

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1770    Accepted Submission(s): 674


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 <= 1015) and (1 <=N <= 109).
 

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}.
 

Source
 

Recommend
lcy   |   We have carefully selected several similar problems for you:  1796 1434 3460 1502 4136 
 

          這道題是要求在A~B範圍中與n互質的數的個數,從反面考慮,用A~B中的所有數的個數減去A~B中與n不互質的數的個數。在計算A~B中與n不互質的數的個數時需要用到容斥原理。

         參考代碼:

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<ctime>
#include<cstdlib>
#include<iomanip>
#include<utility>
#define pb push_back
#define mp make_pair
#define CLR(x) memset(x,0,sizeof(x))
#define _CLR(x) memset(x,-1,sizeof(x))
#define REP(i,n) for(int i=0;i<n;i++)
#define Debug(x) cout<<#x<<"="<<x<<" "<<endl
#define REP(i,l,r) for(int i=l;i<=r;i++)
#define rep(i,l,r) for(int i=l;i<r;i++)
#define RREP(i,l,r) for(int i=l;i>=r;i--)
#define rrep(i,l,r) for(int i=1;i>r;i--)
#define read(x) scanf("%d",&x)
#define put(x) printf("%d\n",x)
#define ll long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<11
using namespace std;
ll a,b,n,t,s;
ll fac[110],cas;
ll dfs(ll idx,ll n)
{
    ll ans=0;
    for(ll i=idx;i<s;i++)
    {
        ll cnt=fac[i];
        ans=ans+(n/cnt);
        ans=ans-dfs(i+1,n/cnt);
    }
    return ans;
}

void get_factor(ll n)
{
    s=0;
    for(ll i=2;i*i<=n;i++)
    {
        if(n%i==0)
        {
            fac[s++]=i;
            while(n%i==0)
                n/=i;
        }
    }
    if(n>1)
        fac[s++]=n;
}

void solve()
{
    get_factor(n);
    ll ans=b-a+1-dfs(0,b)+dfs(0,a-1);
    printf("Case #%I64d: %I64d\n",cas++,ans);
}

int main()
{
   scanf("%I64d",&t);
   cas=1;
   while(t--)
   {
       scanf("%I64d%I64d%I64d",&a,&b,&n);
       solve();
   }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章