P2568 GCD (Euler function, two-dimensional plane thinking)

topic description

Given a positive integer n, find how many pairs (x,y) are there for which 1≤x,y≤n and gcd(x,y) is prime.

input format

There is only one integer per line, representing n.

output format

One integer per line represents the answer.

Input and output samples

Type #1 to copy

4

output #1 copy

4

Instructions/Tips

Sample input and output 1 Explanation

For the example, (x,y) satisfying the condition is (2,2), (2,4), (3,3)(4,2).


Data Size and Conventions

  • For 100% of the data, 1≤n≤107 is guaranteed.

Parse:

First of all, we must first understand the meaning of the question: gcd(x,y) is the greatest common divisor. This question means that the greatest common divisor is a prime number.

Such as gcd (2, 2) = 2, 2 is a prime number.

Thinking of two-dimensional coordinates, it can be seen from the two-dimensional coordinates that their symmetry is y=x;

Under this condition, the formula can be simplified here

 

 This is to solve the numbers that are mutually prime between 0~n/x (x is a prime number).

The definition of the Euler function is: the number of mutual primes to n within the range of n.

Here someone will ask gcd (2, 2) = 2, it can be transformed into gcd (1, 1) = 1.

Euler function f(1) = 1;

In this way, you can successfully ask for it.

sum[3] is the number of relative primes on the left side of the vertical line. 

code;

#include<iostream>
using namespace std;
const int N = 1e7 + 10;
int prime[N];
int visit[N];
int pho[N];
long long sum[N];
int cnt = 0;
void get_ou(int n) {
	pho[1] = 1;
	
	for (int i = 2; i <= n; i++) {
		if (!visit[i]) {
			visit[i] = i;
			pho[i] = i - 1;
			prime[cnt++] = i;
		}
		for (int j = 0; j < cnt; j++) {
			if (prime[j] * i > N) {
				break;
			}
			visit[i * prime[j]] = prime[j];//表示最小的质因子
			if (i % prime[j] == 0) {
				pho[i * prime[j]] = pho[i] * prime[j];
				break;
			}
			pho[i * prime[j]] = pho[i] * pho[prime[j]];
		}
	}
	for (int i = 2; i < N; i++) {
		sum[i] = sum[i - 1] + pho[i];
	}
}
int main() {
	
	int n;
	cin >> n;
	get_ou(n);
	long long res = 0;
	for (int i = 0; i < cnt; i++) {
		res += sum[n / prime[i]] * 2 + 1; // 加1 是 还有(1,1)
	}
	cout << res<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/zhi6fui/article/details/129592713