给定整数N,求1<=x,y<=N且Gcd(x,y)为素数的
数对(x,y)有多少对.
给定整数N,求1<=x,y<=N且Gcd(x,y)为素数的
数对(x,y)有多少对.
一个整数N
如题
hint
对于样例(2,2),(2,4),(3,3),(4,2)
1<=N<=10^7
湖北省队互测
解法①:莫比乌斯函数 分块加速3724ms
gcd(a, b) = prime,又因为gcd(a/prime, b/prime) = prime,即求n/prime[i]内互质的对数,枚举下n以内的质数即可。
# include
# include
# include
# define ll long long
using namespace std;
const int maxn = 1e7;
short mu[maxn+3];
int prime[maxn+3];
bool bo[maxn+3];
int n;
void get_table()
{
mu[1] = 1;
memset(bo, 0, sizeof(bo));
for(int i=2; i<=maxn; ++i)
{
if(!bo[i])
{
prime[++prime[0]] = i;
mu[i] = -1;
}
for(int j=1; j<=prime[0] && i*prime[j]<=maxn; ++j)
{
bo[i*prime[j]] = 1;
if(i%prime[j] == 0)
{
mu[i*prime[j]] = 0;
break;
}
else
mu[i*prime[j]] = -mu[i];
}
}
for(int i=1; i
解法②:欧拉函数 5544ms
打个欧拉函数表,phi[n]表示小于等于n且与n互质的数的个数,求个前缀和即可。
欧拉函数一些定理:phi[p] = p-1,(p为素数),phi[x*p] = phi[x]*p(p为素数,且p为x的因子),phi[x*p] = phi[x]*(p-1)(p为素数,且p不为x的因子),打表就是根据这些规律打的。
# include
# include
# include
# define ll long long
using namespace std;
const int maxn = 1e7;
ll phi[maxn+3];
int prime[maxn+3];
bool bo[maxn+3];
int n;
void make_table()
{
phi[1] = 1;
memset(bo, 0, sizeof(bo));
for(int i=2; i<=maxn; ++i)
{
if(!bo[i])
{
prime[++prime[0]] = i;
phi[i] = i-1;
}
for(int j=1; j<=prime[0] && i*prime[j]<=maxn; ++j)
{
int k = i*prime[j];
bo[k] = 1;
if(i % prime[j]==0)
{
phi[k] = phi[i]*prime[j];
break;
}
else
phi[k] = phi[i]*(prime[j]-1);
}
}
for(int i=1; i<=maxn; ++i)
phi[i] += phi[i-1];
}
int main()
{
make_table();
while(~scanf("%d",&n))
{
ll ans = 0;
int i;
for(i=1; i<=prime[0]&&n/prime[i]; ++i)
ans += phi[n/prime[i]];
--i;
printf("%lld\n",(ans<<1)-i);
}
return 0;
}