编程求2~n(n为大于2的正整数)中有多少个素数。

这是题目

#include<iostream>
#include<cmath>
using namespace std;
bool judge(int x);
int main()
{
    int n;
    int i;
    int sum=0;
 
    cin>>n;
    for(i=2; i<=n; i++)
        if(judge(i))//若是素数
            sum++;//累加素数个数
    cout<<sum<<endl;
 
    return 0;
}
bool judge(int x)//判断素数
{
    int i=2;
    while(i<=floor(sqrt(x))&&(x%i)!=0)
        i++;
    if(i>floor(sqrt(x)))
        return true;
    return false;
}

这是我的代码

在其中我用了一个bool型变量进行对素数的判别,

因为这个题是对个数进行统计所以我在main函数中用for循环打了一个计数器

就是sum,最后输出sum就行了

这就是这个题了

 

相关文章:

  • 2021-07-19
  • 2021-06-28
  • 2021-10-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-20
  • 2022-12-23
猜你喜欢
  • 2022-01-09
  • 2021-08-19
  • 2021-11-12
  • 2021-10-18
  • 2021-08-18
  • 2021-05-26
相关资源
相似解决方案