HDU1695:GCD(莫比乌斯函数)

来源:互联网 发布:做微商可以淘宝进货吗 编辑:程序博客网 时间:2024/06/05 07:06

GCD

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


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
21 3 1 5 11 11014 1 14409 9
 

Sample Output
Case 1: 9Case 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
2008 “Sunline Cup” National Invitational Contest
题意:给出b,d,k,求1~b与1~d内gcd为k的二元组种数,其中形如(3,4)和(4,3)的视为同一种。

思路:用莫比乌斯函数,大概就是容斥原理的队列数组形式那样子,先转化题目的意思,gcd(x, y) = k,即gcd(x/k, y/k) = 1,所以即求1~b/k与1~d/k内互质的对数。那么我们知道若两数互质,他们的质因数种类一定是不同的,据此容斥即可。

# include <iostream># include <cstdio># include <cstring># include <algorithm># define maxn 100000# define ll long longusing namespace std;int a, b, c, d, k,cas=1;int prime[maxn+3];short mu[maxn+3];bool bo[maxn+3];void get_table()//莫比乌斯。{    mu[1] = 1;    memset(bo, 0, sizeof(bo));    for(int i=2; i<=maxn; ++i)    {        if(!bo[i])        {            prime[++prime[0]] = i;            mu[i] = -1;        }        for(int j=1; j<=prime[0]&&prime[j]*i<=maxn; ++j)        {            bo[i*prime[j]] = 1;            if(i % prime[j] == 0)            {                mu[i*prime[j]] = 0;                break;            }            else                mu[i*prime[j]] = -mu[i];        }    }}void solve(){    b /= k;    d /= k;    ll ans=0, rep=0;    if(b>d) swap(b, d);    for(int i=1; i<=b; ++i)    {        ans += (ll)mu[i]*(b/i)*(d/i);        rep += (ll)mu[i]*(b/i)*(b/i);//用于去重。    }    printf("Case %d: %lld\n",cas++, ans-(rep>>1));}int main(){    int t;    scanf("%d",&t);    get_table();    while(t--)    {        scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);        if(k == 0)            printf("Case %d: 0\n",cas++);        else            solve();    }    return 0;}



0 0
原创粉丝点击