简体   繁体   中英

finding given amount of prime number

The wrote this program that is supposed to find a given number (n) of prime numbers, beginning with 2. I can't seem to find the issue, Im not getting any error messages, however, I am not getting the any output at all. Any help would be greatly appreciated.

#include<cmath>
#include<cstdlib>
#include<string>
#include<list>
#include <forward_list>
#include<vector>
#include<unordered_map>
#include<algorithm>
#include <array>
#include <regex>
#include<random>
#include<stdexcept>

using namespace std;
bool is_prime(int a);

int main()
{
    cout<<"Give me the number of primes you want: \n";
    int n;
    cin>>n;

    vector<int> primes;
    int i = 2;
    int count = 0;
    while (n < count)
    {
        if (is_prime(i))
        {
            primes.push_back(i);
            count++;
        }
        i++;

    }
    for (int i = 0; i < primes.size(); i++)
        cout<<"Prime number: "<< i + 1 << "\t"<< primes[i] <<endl;

}

bool is_prime(int a)
{
    if (a <= 1)
        return false;
    else if (a == 2)
        return true;
    for (int i = 2; i < a; i++)
    {
        if (a % i == 0)
            return false;
    }
    return true;

};

Your bug is here:

int count = 0;
while (n < count)

What do you think happens when (n < count) is evaluated?

Usual suggestions for prime number detections:

  1. Your loop only needs to test for divisibility up to sqrt(a) .
  2. Your loop only needs to test for divisibility with odd numbers (after checking explicitly for the 2 case)

That is:

int stop = (int)sqrt(a);
for (int i = 3; i <= stop; i+=2)
{
  …
  1. And if you really want to be performant, since you are accumulating primes into a vector, you really only need to test a for divisibility with the primes you have already confirmed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM