c++ - 计算两个数之间质数个数的函数

标签 c++

我正在尝试计算两个数字之间素数的个数,我的程序运行良好,但打印出答案加 1。我不确定我的素数检查器出了什么问题。在 1-100 之间检查时,我得到 26 而不是 25。

#include <iostream>
using namespace std;

int number_of_primes(int from, int to){

    int count=0;
    for (int a=from ; a < to ; a++)
    {
        bool prime = true;
        for (int c=2 ; c*c <= a ; c++)
        {
            if(a % c == 0)
            {
                prime = false;
                break;
            }
         }
        if(prime) count++;
    }


return count;

}

int main(){

int a=1;
int b=100;

cout<<number_of_primes(a, b)<<endl;

return 0;

}

最佳答案

你在计数中包含了 1,跳过它:

int number_of_primes(int from, int to) {

    int count = 0;
    for (int a = from; a < to; a++)
    {
        if (a == 1)
            continue; // Skip 1
        ...

否则,正如 Mark 所建议的,您不妨这样做:

a = max(from, 2) // Disallow 1/0 values

其余代码是正确的。

关于c++ - 计算两个数之间质数个数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26643243/

相关文章:

c++ - 如何延长成员引用的生命周期?

c++ - 在 Windows 上存储信息有哪些选项?我应该如何阅读这些信息?

c++ - 在不调用 main 方法的情况下运行 Boost.Test

c++ - offsetof 可以与从 decltype 获得的结构类型一起使用吗?

c++ - 关闭 ifstream 后 vector 下标超出范围

c++ - 复制构造函数和抛出表达式

c++ - 在 Doom3 的源代码中,为什么他们使用 bitshift 来生成数字而不是硬编码?

c++ - c++资源文件管理

c++ - 如果 operator<< 重载,VSCode 表示 std::chrono 不明确

c++ - 多线程 - 在一个线程中增加整数并在另一个线程中减少