【问题标题】:Counting prime numbers in C++ [closed]在 C++ 中计算素数 [关闭]
【发布时间】:2025-12-14 22:25:02
【问题描述】:

如何计算所有“质数”而不是显示它们?

例子:

cout << "there are 125 prime numbers";

我使用数字 1000 是因为我想知道它有多少个素数。

我不想显示找到的素数,但我想知道找到了多少。

#include <iostream> 
#include <iomanip> 
#include <string>
#include <sstream> 
#include <fstream> 
#include <math.h> 
#include <stdio.h>

using namespace std;

int main()
{
    for (int a=2 ; a < 1000 ; a++)
    {
        bool prime = true;

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

        if(prime) cout << a << " ";
    }

    return 0;
}

【问题讨论】:

  • 你的格式化人..它..很糟糕。
  • 您知道这是所见即所得,并且在您编写问题时右侧有一个格式帮助框,对吧?
  • 您为什么不尝试以正确的方式提出问题。此外,您的问题可以通过简单的谷歌搜索来回答。是的,看看 Eratosthenes 的筛子。
  • 这就是我要问的原因,否则我什么都不会说...我不明白为什么要发布没有任何积极意义的 cmets 来为我的问题提供答案...
  • 只需为每个质数使用一个计数器。增加计数器而不是显示每个素数。最后,打印计数器的值。这真的与素数无关。

标签: c++ primes


【解决方案1】:

重新格式化您的代码:

#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
#include <math.h>
#include <stdio.h>

using namespace std;

int main() {
    for (int a = 2; a < 1000; a++) {
        bool prime = true;

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

         if(prime) cout << a << " ";
    }

    return 0;
}

不是每次都通过循环打印出来,而是需要创建一个变量来在每次数字为素数时进行计数。首先在外部 for 循环之外添加一个变量:

int main() {
    int num_primes = 0;
    for (int a = 2; a < 1000; a++) {

接下来,不要在数字为素数时打印,而是增加计数器:

if(prime) {
    num_primes += 1;
}

最后,在你从 main() 返回之前,打印出素数的数量:

cout << num_primes << endl;
return 0;

虽然这看起来像是你的作业,但我希望你能从中学到一些东西。

【讨论】:

  • 谢谢...大部分代码都是由我设计的,只是当涉及到细节时,我倾向于放松指南......解释c ++的指南并不多......感谢您澄清我的代码...
  • 请问“+=”是做什么的?
  • 它是“num_primes = num_primes + 1”的简写。这不是最好的方法,但我试图尽可能少地更改您的代码。
【解决方案2】:

试试这个,

#include < iostream>
#include < iomanip>
#include < string>
#include < sstream>
#include < fstream>
#include < math.h>
#include < stdio.h>

using namespace std;
int main()
{
    int count=0;
    for (int a=2 ; a < 1000 ; a++)
    {
        bool prime = true;
        for (int c=2 ; c*c <= a ; c++)
        {
            if(a % c == 0)
            {
                prime = false;
                break;
            }
         }
        if(prime) count++;
    }

    cout <<"No of prime numbers : "<< count;
    return 0;
}

【讨论】:

  • 谢谢它的工作......我永远不会猜到这种细节......
  • 请避免使用 "Try [Insert code sn-p here]" 答案。提供一些解释。如果不这样做,建议OP只复制粘贴答案,不理解和思考。
【解决方案3】:

简单,只需增加一个计数器而不是打印值。您还可以使用等式 N/(log(N)-1) 获得欧拉总函数的相当不错的近似值...

【讨论】:

  • 那么我该如何准确地实现一个计数器...我是 C++ 和词汇的新手...
  • 参见上面 RadhaKrishna 的帖子。