【SPOJ-GCDEX】GCD Extreme【欧拉函数】【线性筛】

题意:

求∑(1 <= i < j <= n) gcd(i, j)。


白书上原题...注意卡常就可以过。


#include <cstdio>

typedef unsigned long long ULL;
typedef unsigned int uint;

const int maxn = 1000001;

int cnt;
int prime[maxn], phi[maxn];
ULL f[maxn];
bool isnotprime[maxn];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

void init() {
	isnotprime[1] = 1; phi[1] = 1;
	for(uint i = 2; i < maxn; i++) {
		if(!isnotprime[i]) prime[++cnt] = i, phi[i] = i - 1;
		for(uint j = 1; j <= cnt && i * prime[j] < maxn; j++) {
			isnotprime[i * prime[j]] = 1;
			if(i % prime[j] == 0) {
				phi[i * prime[j]] = phi[i] * prime[j];
				break;
			}
			phi[i * prime[j]] = phi[i] * phi[prime[j]];
		}
	}
	for(uint i = 1; i < maxn; i++) for(uint j = i + i; j < maxn; j += i) f[j] += i * phi[j / i];
	for(int i = 1; i < maxn; i++) f[i] += f[i - 1];
}

int main() {
	init();
	while(1) {
		int n = iread();
		if(n == 0) break;
		printf("%llu\n", f[n]);
	}
	return 0;
}


你可能感兴趣的:(欧拉函数,线性筛)