zoukankan      html  css  js  c++  java
  • Prime Number(求n内质数的个数)

    Description

    Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

    Input

    Input consists of several datasets. Each dataset has an integer n (1 ≤ n ≤ 999,999) in a line.

    The number of datasets is less than or equal to 30.

    Output

    For each dataset, prints the number of prime numbers.

    Sample Input

    10
    3
    11
    

    Output for the Sample Input

    4
    2
    5
    解题思路:题意很简单,求n内质数的个数,注意n最大也就1e6,既可用埃氏筛也可以用欧拉筛模板,水过!
    AC代码:
     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 const int maxn=1e6+5;
     4 int n,cnt=0,prime[maxn];bool isp[maxn];
     5 void euler_sieve(){
     6     memset(isp,true,sizeof(isp));
     7     isp[0]=isp[1]=false;
     8     for(int i=2;i<maxn;++i){
     9         if(isp[i])prime[cnt++]=i;
    10         for(int j=0;j<cnt&&i*prime[j]<maxn;++j){
    11             isp[i*prime[j]]=false;
    12             if(i%prime[j]==0)break;
    13         }
    14     }
    15 }
    16 int main(){
    17     euler_sieve();
    18     while(~scanf("%d",&n)){
    19         int num=0;
    20         for(int i=0;prime[i]<=n&&i<cnt;++i)num++;
    21         printf("%d
    ",num);
    22     }
    23     return 0;
    24 }
  • 相关阅读:
    C语言运算符优先级和口诀
    跨域问题的解决方案 php
    浅谈跨域攻击及预防
    浅析Websocket--PHP
    linux下的删除目录和文件的方法
    python魔法方法
    双指针
    python常用模块
    python三大器
    对闭包的误区
  • 原文地址:https://www.cnblogs.com/acgoto/p/9491308.html
Copyright © 2011-2022 走看看