编程介的小学生 2019-01-28 23:36 采纳率: 20.5%
浏览 2890

给定一个区间以内,求其中素数的个数,采用C语言方式的实现

Problem Description
Easy question! Calculate how many primes between [1...n]!

Input
Each line contain one integer n(1 <= n <= 1e11).Process to end of file.

Output
For each case, output the number of primes in interval [1...n]

Sample Input
2
3
10

Sample Output
1
2
4

  • 写回答

1条回答 默认 最新

  • wuerlongxin 2019-01-29 11:25
    关注
    #include <stdio.h>
    #include<math.h>
    
    
    bool isPrime(long num)
    {
        long i = 2;
        if(num <= 1)
        {
            return false;
        }
    
        long sqrNum = sqrt(num);
    
        for(i = 2; i <= sqrNum; i++)
        {
            if(num % i == 0)
            {
                return false;
            }
        }
        return true;
    }
    
    int getPrimeCount(long a)
    {
        int sum = 0;
        long start;
    
        if(a <= 1)
        {
            return 0;
        }
    
        for(start = 2; start <= a; start++)
        {
            if(isPrime(start))
            {
                sum++;
            }
        }
        return sum;
    }
    
    int main()
    {
        long a;
        scanf("%ld", &a);
        printf("%d\n", getPrimeCount(a));
        return 0;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常