[BZOJ2818]Gcd

[BZOJ2818]Gcd

试题描述

给定整数N,求1<=x,y<=N且Gcd(x,y)为素数的
数对(x,y)有多少对.

输入

一个整数N

输出

如题

输入示例

4

输出示例

4

数据规模及约定

1<=N<=10^7

题解

对于每个质数 p,求数对 (x, y) ∈ [1, n] 满足 gcd(x, y) = p 的对数等价于求数对 (x, y) ∈ [1, n / p] 满足 x, y 互质的对数。不妨设 x ≤ y,对于每一个 y,比它小的 x 个数等于 phi(y).

然后线性筛预处理一下 phi 和 phi 的前缀和,枚举每个素数累计答案即可。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;

const int BufferSize = 1 << 16;
char buffer[BufferSize], *Head, *Tail;
inline char Getchar() {
	if(Head == Tail) {
		int l = fread(buffer, 1, BufferSize, stdin);
		Tail = (Head = buffer) + l;
	}
	return *Head++;
}
int read() {
	int x = 0, f = 1; char c = Getchar();
	while(!isdigit(c)){ if(c == '-') f = -1; c = Getchar(); }
	while(isdigit(c)){ x = x * 10 + c - '0'; c = Getchar(); }
	return x * f;
}

#define maxn 10000010
#define LL long long
int n;
LL sum[maxn];

int prime[maxn], cnt, phi[maxn];
bool vis[maxn];
void phi_table() {
	int N = maxn - 10;
	for(int i = 2; i <= N; i++) {
		if(!vis[i]) prime[++cnt] = i, phi[i] = i - 1;
		for(int j = 1; j <= cnt && (LL)prime[j] * (LL)i <= (LL)N; j++) 
			if(i % prime[j]) phi[i*prime[j]] = phi[i] * (prime[j] - 1), vis[i*prime[j]] = 1;
			else{ vis[i*prime[j]] = 1; phi[i*prime[j]] = phi[i] * prime[j]; break; }
	}
	return ;
}

int main() {
	phi_table();
	n = read();
	
	for(int i = 1; i <= n; i++) sum[i] = sum[i-1] + (LL)phi[i];
//	for(int i = 1; i <= n; i++) printf("%lld ", sum[i]); putchar('\n');
	LL ans = 0;
	for(int i = 1; i <= cnt && prime[i] <= n; i++) ans += (sum[n/prime[i]] << 1ll) + 1ll;
	
	printf("%lld\n", ans);
	
	return 0;
}

 

posted @ 2016-08-21 13:19  xjr01  阅读(240)  评论(0编辑  收藏  举报