求区间x∈[1,n],y∈[1,m],gcd(x,y)=1的数量 [容斥]

本文介绍了一种解决特定数学问题的方法:计算在一个由树木组成的m*n网格中,从起点(0,0)能看到多少棵树。当三棵树在同一直线上时,只能看到离观察者最近的一棵。通过算法计算互质数对的数量来得出最终答案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description

There are many trees forming a m * n grid, the grid starts from (1,1). Farmer Sherlock is standing at (0,0) point. He wonders how many trees he can see.

If two trees and Sherlock are in one line, Farmer Sherlock can only see the tree nearest to him.

InputOutput
The first line contains one integer t, represents the number of test cases. Then there are multiple test cases. For each test case there is one line containing two integers m and n(1 ≤ m, n ≤ 100000)For each test case output one line represents the number of trees Farmer Sherlock can see.

样例

Sample InputSample Output
2
1 11
2 35

解题报告

设:

G(N)=[1,m]N

该问题就是求:

i=1nG(N)

代码如下:

//求区间x[1,n],y[1,m],gcd(x,y)==1的数量
#include<stdio.h>
#define MAX_C 32
typedef long long LL;
int cs[MAX_C],u;

int slove(int m,int n){
    u=0;
    for(int i=2;i*i<=n;i++)
        if(n%i==0){
            cs[u++]=i;
            while(n%i==0) n/=i;
        }
    if(n>1) cs[u++]=n;

    int ans=0;
    for(int i=1;i<(1<<u);i++){
        int cnt=0,res=1;
        for(int k=0;k<u;k++)
            if(i>>k&1){
                res*=cs[k];
                cnt++;
            }
        ans+=cnt&1?m/res:-m/res;
    }
    return m-ans;
}

int main()
{
    int T,a,b;
    scanf("%d",&T);
    while(T--){
        scanf("%d%d",&a,&b);
        LL ans=0; //一组不超int 但是1e5组可能超
        for(int i=1;i<=a;i++)
            ans+=slove(b,i);
        printf("%lld\n",ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值