HDU 1695-GCD(容斥原理+尤拉函式)

kewlgrl發表於2016-08-05

GCD

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9601    Accepted Submission(s): 3582


Problem Description
Given 5 integers: a, b, c, d, k, you're to find x in a...b, y in c...d that GCD(x, y) = k. GCD(x, y) means the greatest common divisor of x and y. Since the number of choices may be very large, you're only required to output the total number of different number pairs.
Please notice that, (x=5, y=7) and (x=7, y=5) are considered to be the same.

Yoiu can assume that a = c = 1 in all test cases.
 

Input
The input consists of several test cases. The first line of the input is the number of the cases. There are no more than 3,000 cases.
Each case contains five integers: a, b, c, d, k, 0 < a <= b <= 100,000, 0 < c <= d <= 100,000, 0 <= k <= 100,000, as described above.
 

Output
For each test case, print the number of choices. Use the format in the example.
 

Sample Input
2 1 3 1 5 1 1 11014 1 14409 9
 

Sample Output
Case 1: 9 Case 2: 736427
Hint
For the first sample input, all the 9 pairs of numbers are (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 5), (3, 4), (3, 5).
 

Source
 

Recommend
wangye   |   We have carefully selected several similar problems for you:  1689 1690 1693 1691 1698 

題目意思:

給出5個數,a,b,c,d,k,在[a,b]閉區間內找一個數x,再在[c,d]中找一個數y,使得(x,y)的最大公約數是k。
請找出滿足條件的不同的(x,y)的對數,其中x與y交換位置視為同一種。

解題思路:

gcd(x,y)=k,則gcd(x/k,y/k)=1。
變換區間,1~b中k的最大倍數為int(b/k)*k,新區間為1~int(b/k),相應另一個新區間為1~int(d/k)。
令 b'=int(b/k),d'=int(d/k),且b'<=d',則新區間為:[1,b']和[b'+1,d']。
前一個區間:[1,b];後一個區間:任取一個數i,求[1,b]內所有能被i的質因數整除的數的個數,然後用b'減去。
#include<bits/stdc++.h>
using namespace std;
#define maxn 100010
typedef long long ll;
int a[maxn];
struct Number
{
    int cnt;//每個數質因數的個數
    int prime[20];//每個數的質因數陣列
} n[maxn];
ll e[maxn];//尤拉函式打表用
void oula()//尤拉函式
{
    e[1]=1;
    memset(n,0,sizeof(Number)*maxn);//初始化清零
    for(int i=2; i<=maxn; ++i)
    {
        if(!e[i])
            for(int j=i; j<=maxn; j+=i)
            {
                if(!e[j]) e[j]=j;
                e[j]=e[j]*(i-1)/i;//尤拉函式打表
                n[j].prime[n[j].cnt++]=i;//儲存質因數
            }
        e[i]+=e[i-1];
    }
}

ll inc(int index,int b,int m)//容斥原理,遞迴
{
    ll r=0,t;
    for(int i=index; i<n[m].cnt; ++i)
    {
        t=b/n[m].prime[i];
        r+=t-inc(i+1,t,m);
    }
    return r;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    oula();//預處理
    int t,ca=0;
    cin>>t;
    while(t--)
    {
        int a,b,c,d,k;
        cin>>a>>b>>c>>d>>k;
        if(k==0)//注意特判
        {
            cout<<"Case "<<++ca<<": 0"<<endl;
            continue;
        }
        if(b>d) swap(b,d);//使得b始終大於d
        b/=k;
        d/=k;
        ll ans=e[b];//前一個區間:[1,b]
        for(int i=b+1; i<=d; ++i)//後一個區間:任取一個數i,求[1,b]內所有能被i的質因數整除的數的個數
            ans+=b-inc(0,b,i);
        cout<<"Case "<<++ca<<": "<<ans<<endl;
    }
    return 0;
}

/**
2
1 3 1 5 1
1 11014 1 14409 9
**/


相關文章