列表

详情


NC17247. H、Diff-prime Pairs

描述

Eddy has solved lots of problem involving calculating the number of coprime pairs within some range. This problem can be solved with inclusion-exclusion method. Eddy has implemented it lots of times. Someday, when he encounters another coprime pairs problem, he comes up with diff-prime pairs problem. diff-prime pairs problem is that given N, you need to find the number of pairs (i, j), where and are both prime and i ,j ≤ N. gcd(i, j) is the greatest common divisor of i and j. Prime is an integer greater than 1 and has only 2 positive divisors.

Eddy tried to solve it with inclusion-exclusion method but failed. Please help Eddy to solve this problem.

Note that pair (i1, j1) and pair (i2, j2) are considered different if i1 ≠ i2 or j1 ≠ j2.

输入描述

Input has only one line containing a positive integer N.

1 ≤ N ≤ 107

输出描述

Output one line containing a non-negative integer indicating the number of diff-prime pairs (i,j) where i, j ≤ N

示例1

输入:

3

输出:

2

示例2

输入:

5

输出:

6

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

pypy3 解法, 执行用时: 1562ms, 内存消耗: 137476K, 提交时间: 2022-04-20 19:24:54

import bisect
n = int(input())
is_prime = [1] * (n+1)
prime = []
ans = 0

for i in range(2, n+1):
    if is_prime[i]:
        prime.append(i)
        for j in range(i*i, n+1, i):
            is_prime[j] = 0

for i in range(1, n+1):
    j = bisect.bisect_right(prime, n/i)
    if j <= 1:
        break
    ans += j * (j-1)
print(ans)

C++14(g++5.4) 解法, 执行用时: 300ms, 内存消耗: 78680K, 提交时间: 2020-10-08 15:55:20

#include <bits/stdc++.h>
using namespace std;
long i=2,j,n,c,s,a[10000001];
main() 
{
    cin>>n;
    for(;i<=n;i++)
        if(!a[i]) 
		{
            s+=c*(n/i);c++;
            for(j=i*i;j<=n;j+=i)a[j]=1;
        }
    cout<<s*2;
}

C++11(clang++ 3.9) 解法, 执行用时: 267ms, 内存消耗: 78676K, 提交时间: 2020-10-08 20:51:22

#include<bits/stdc++.h>
using namespace std;
long i=2,j,n,c,s,a[10000001];
int main()
{
	cin>>n;
	for(;i<=n;i++)
	if(!a[i])
	{
		s+=c*(n/i);
		c++;
		for(j=i*i;j<=n;j+=i)
		a[j]=1;
	}
	cout<<s*2;
 } 

上一题