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.
Input
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)
Output
For each test case output one line represents the number of trees
Farmer Sherlock can see.
Sample Input
2
1 1
2 3
Sample Output
1
5
思路
题目转化一下就可以变成:已知 x∈[1,n] x ∈ [ 1 , n ] , y∈[1,m] y ∈ [ 1 , m ] 求x和y这两个集合中互质的数的个数。
利用容斥,枚举x集合,然后暴力加起来
代码
#include <cstdio>
#include <cstring>
#include <cctype>
#include <stdlib.h>
#include <string>
#include <map>
#include <iostream>
#include <stack>
#include <cmath>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
#define inf 1000000
#define mem(a,b) memset(a,b,sizeof(a))
ll a[50],b[1010];//a保存n的质因子,a[0]表示质因子个数
void div(ll n)//分解质因数
{
ll j=0;
for(ll i=2; i*i<=n; i++)
if(n%i==0)
{
while(n%i==0)
n/=i;
a[++j]=i;
}
if(n>1) a[++j]=n;
a[0]=j;
}
ll get_cnt(ll mid)//1--mid之间与n互质的数有多少个
{
ll g=0,sum=mid,t;
b[++g]=1;
for(ll i=1; i<=a[0]; i++)
{
t=g;
for(ll j=1; j<=g; j++)
{
b[++t]=b[j]*a[i]*-1;
sum+=mid/b[t];
}
g=t;
}
return sum;
}
int main()
{
ll t,n,m;
scanf("%lld",&t);
while(t--)
{
mem(a,0);
mem(b,0);
ll ans=0;
scanf("%lld%lld",&n,&m);
for(ll i=1; i<=n; i++)
{
div(i);
ans+=get_cnt(m);
}
printf("%lld\n",ans);
}
return 0;
}