【洛谷】P3912 素数个数

题目地址:

https://www.luogu.com.cn/problem/P3912

题目描述:
1 , 2 , ⋯   , N 1,2,\cdots,N 1,2,,N中素数的个数。

输入格式:
一行一个整数 N N N

输出格式:
一行一个整数,表示素数的个数。

数据范围:
对于 40 % 40\% 40%的数据, 1 ≤ N ≤ 1 0 6 1 \le N \le 10^6 1N106
对于 80 % 80\% 80%的数据, 1 ≤ N ≤ 1 0 7 1 \le N \le 10^7 1N107
对于 100 % 100\% 100%的数据, 1 ≤ N ≤ 1 0 8 1 \le N \le 10^8 1N108

直接用欧拉筛。参考https://blog.csdn.net/qq_46105170/article/details/113813830。代码如下:

#include <iostream>
using namespace std;

const int N = 1e8 + 10;
int n;
int p[N], cnt;
bool st[N];

void get_prime() {
  for (int i = 2; i <= n; i++) {
    if (!st[i]) p[cnt++] = i;
    for (int j = 0; p[j] <= n / i; j++) {
      st[p[j] * i] = true;
      if (i % p[j] == 0) break;
    }
  }
}

int main() {
  scanf("%d", &n);
  get_prime();
  printf("%d\n", cnt);
}

时空复杂度 O ( N ) O(N) O(N)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值