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.
题意:
在m*n的方格中,每个里面有一棵树(从(1,1)到(m,n)),你在(0,0),问可以看到几棵树
解题思路:
很明显,第一排和第一列都可以看到,那么后面的呢。。。。。我也是看了别人的博客才知道,如果一个一棵树的坐标(x,y),
x,y互质,则可以看到,所以题目就是求,有多少对坐标是互质的。
枚举第一行的每一个元素,看所在的列有多少个数与之互质,全都加起来即可
所以问题又变为了,在区间1~n之间,有多少个数与x互质,(欧拉函数是1~n之间与n互质的个数),so这里就用容斥定理解决
容斥定理的模板和简单介绍:https://blog.youkuaiyun.com/qq_40733911/article/details/81705233
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int fac[100000];
int div(int n)
{
int cnt=0;
for(int i=2;i*i<=n;i++)
{
if(n%i==0)
{
fac[cnt++]=i;
while(n%i==0) n/=i;
}
}
if(n>1) fac[cnt++]=n;
return cnt;
}
int solve(int n,int cnt)
{
int ans=0;
for(int i=1;i< (1<<cnt);i++)
{
int ones=0,mult=1;
for(int j=0;j<cnt;j++)
{
if(i & (1<<j))
{
ones++;
mult*=fac[j];
}
}
if(ones &1)
ans+= n/mult;
else
ans-= n/mult;
}
return n-ans;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n,m;
ll ans=0;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
int cnt=div(i);
ans+= solve(m,cnt);
}
cout<<ans<<endl;
}
return 0;
}