Visible Trees
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1280 Accepted Submission(s): 530
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.
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
Source
2009 Multi-University Training Contest 3 - Host by WHU
有一个方阵n*m棵树,一个人站在0,0的位置,假设两棵树处在同一条直线上,那么只能看见第一棵树,后面的都被挡了,问总共能看到多少棵树。
很明显是求互素对数,可以枚举小于m的数,对其进行质因子分解,然后容斥统计在小于n的数里与其互质的数的个数,
代码:
有一个方阵n*m棵树,一个人站在0,0的位置,假设两棵树处在同一条直线上,那么只能看见第一棵树,后面的都被挡了,问总共能看到多少棵树。
很明显是求互素对数,可以枚举小于m的数,对其进行质因子分解,然后容斥统计在小于n的数里与其互质的数的个数,
代码:
/* ***********************************************
Author :rabbit
Created Time :2014/4/2 14:21:05
File Name :13.cpp
************************************************ */
#pragma comment(linker, "/STACK:102400000,102400000")
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <string>
#include <time.h>
#include <math.h>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
typedef __int64 ll;
bool isprime[1001000];
ll prime[1001000],factor[1010];
void getprime(){
memset(isprime,1,sizeof(isprime));isprime[1]=0;
ll &cnt=prime[0];cnt=0;
for(ll i=2;i<=1000000;i++){
if(isprime[i])prime[++cnt]=i;
for(ll j=1;j<=cnt&&i*prime[j]<=1000000;j++){
isprime[i*prime[j]]=0;
if(i%prime[j]==0)break;
}
}
// cout<<prime[0]<<endl;
}
void getfactor(ll x){
ll &cnt=factor[1000];cnt=0;
for(ll i=1;i<=prime[0]&&prime[i]*prime[i]<=x;i++)
if(x%prime[i]==0){
factor[cnt++]=prime[i];
while(x%prime[i]==0)x/=prime[i];
}
if(x>1)factor[cnt++]=x;
}
ll cal(ll x){
ll cnt=factor[1000],ans=0;
for(ll i=1;i<(1<<cnt);i++){
ll pp=1,ss=0;
for(ll j=0;j<cnt;j++)
if(i&(1<<j)){
ss++;pp*=factor[j];
}
if(ss%2)ans+=x/pp;
else ans-=x/pp;
}
return x-ans;
}
int main()
{
//freopen("data.in","r",stdin);
//freopen("data.out","w",stdout);
getprime();
int T;
scanf("%d",&T);
for(int t=1;t<=T;t++){
ll N,M;
scanf("%I64d%I64d",&N,&M);
ll ans=N;
for(ll i=2;i<=M;i++){
getfactor(i);
ans+=cal(N);
}
cout<<ans<<endl;
}
return 0;
}