[英]finding given amount of prime number
寫了這個程序應該找到一個給定數量(n)的素數,從2開始。我似乎無法找到問題,我沒有收到任何錯誤信息,但是,我沒有得到任何輸出所有。 任何幫助將不勝感激。
#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;
};
你的錯誤在這里:
int count = 0;
while (n < count)
當(n < count)
被評估時你認為會發生什么?
質數檢測的常用建議:
sqrt(a)
可分性。 2
案例后) 那是:
int stop = (int)sqrt(a);
for (int i = 3; i <= stop; i+=2)
{
…
a
可分性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.