HDU 1695 GCD (容斥原理+质因数分解)

先进行预处理,对每一个数分解质因数。

然后将因为若gcd(x,y)==z,那么gcd(x/z,y/z)==1,又因为不是z的倍数的肯定不是,所以不是z的倍数的可以直接去掉,所以只要将b和d除以k,然后就转化成了求两个范围中互质的对数了。这时候可以枚举1~b,然后用容斥原理找1~d范围内的与枚举数互质的数的个数,为了避免重复,只要再限定下大小关系就可以了,具体见代码。

代码如下:

#include <iostream>
#include <string.h>
#include <math.h>
#include <queue>
#include <algorithm>
#include <stdlib.h>
#include <map>
#include <set>
#include <stdio.h>
using namespace std;
#define LL __int64
const int mod=1e9+7;
const int INF=0x3f3f3f3f;
LL ans;
LL a, b, c, d;
vector<int>vec[110000];
void dfs(LL i, int cur, int cnt, LL tmp)
{
        tmp*=(LL)vec[i][cur];
        if(cnt&1) {
                ans+=(LL)min(d,i)/tmp;
        } else {
                ans-=(LL)min(d,i)/tmp;
        }
        for(int j=cur+1; j<vec[i].size(); j++) {
                dfs(i,j,cnt+1,tmp);
        }
}
void init()
{
        int i, j, x, cnt;
        for(i=1; i<=100000; i++) {
                x=i;
                cnt=0;
                for(j=2; j*j<=x; j++) {
                        if(x%j==0) {
                                vec[i].push_back(j);
                                while(x%j==0) x/=j;
                        }
                }
                if(x>1)
                        vec[i].push_back(x);
        }
}
int main()
{
        int t, i, j, num=0;
        LL sum, k;
        init();
        scanf("%d",&t);
        while(t--) {
                scanf("%I64d%I64d%I64d%I64d%I64d",&a,&b,&c,&d,&k);
                num++;
                if(!k) {
                        printf("Case %d: 0\n",num);
                        continue ;
                }
                b/=k;
                d/=k;
                if(b<d)
                        swap(b,d);
                sum=d*(d+1)/2+(b-d)*d;
                ans=0;
                for(i=1; i<=b; i++) {
                        for(j=0; j<vec[i].size(); j++) {
                                dfs(i,j,1,1);
                        }
                        //printf("%I64d\n",ans);
                }
                //printf("%I64d   %I64d\n",sum,ans);
                printf("Case %d: %I64d\n",num,sum-ans);
        }
        return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值