【HDU 1695】 【P3455】[POI2007]ZAP-Queries

GCD

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

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

題解

這個題要求i=1nj=1m[gcd(i,j)==k]
我們設
g(n) 表示gcd(i,j)modn=0 的數量。
f(n) 表示gcd(i,j)=n 的數量。
顯然
g(n)=n|df(d)
進行莫比烏斯反演得到:
f(n)=n|du(dn)g(d)
我們把n,m/k ,就相當於求
i=1nkj=1mk[gcd(i,j)==1]
這時我們發現
g(i)=nimi
帶入莫比烏斯反演得到的式子就可以得到:
f(i)=i|du(di)ndmd
我們要求的是f(1) ,直接枚舉就可以,可以利用整除分塊,把複雜度降至O(n+m)

代碼

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#define ll long long 
#define N 1000020
const int MAXN=1e7;
using namespace std;
ll a,T,b,k,n;
int pre[MAXN],mu[MAXN],vis[MAXN],S_mu[MAXN],num;
void Init()
{
    mu[1]=1;
    for(int i=2;i<=N;i++)
    {
        if(vis[i]==0) pre[++num]=i,mu[i]=-1;
        for(int j=1;j<=num&&pre[j]*i<=N;j++)
        {
            vis[pre[j]*i]=1;
            if(i%pre[j]==0)
            {
                mu[pre[j]*i]=0;
            }
            else
                mu[pre[j]*i]=-mu[i];
        }
    }
    for(int i=1;i<=N;i++) S_mu[i]=S_mu[i-1]+mu[i];
}
int main()
{
    Init();
    scanf("%lld",&T);
    while(T--)
    {
        scanf("%lld%lld%lld",&a,&b,&k);
        ll ans=0;
        a/=k;
        b/=k;
        for(ll i=1,j=0;i<=min(a,b);i=j+1)
        {
            j=min(a/(a/i),b/(b/i));
            ans+=(S_mu[j]-S_mu[i-1])*(a/i)*(b/i);
        }
        printf("%lld\n",ans);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章