/*Print the first N prime numbers based on user input*/
#include<iostream>
#include<cmath>
using namespace std;
bool isPrime(int N) {
if (N <= 0) {return false;}
double L = sqrt(N);
for (int i=2; i<=L; i++) {
if (N%i == 0) {return false;}
}
return true;
}
int main()
{
int Q = 0; //# of prime numbers to be found
int C = 0; //That's the counter
int I = 2; //Number to be check
cout<<"Number of prime numbers needed: ";
cin>>Q;
int primes [Q];
while (true) {
if (C == Q) {break;}
if (isPrime(I)) {
primes[C] = I;
C++;
I++;
}
}
for (int i=0; i<Q; i++) {
cout<<primes[i]<<endl;
}
return 0;
}
這並不工作,並隨時打印2和1個屏幕,而不是質數列表,使用isPrime功能無法正常工作,可能出錯了我的數組C++數組長度可變行不通
可變大小的數組是不是標準的C改變這種++,我建議使用'的std :: VECTOR'代替 – Slava
你確定只想增加我只有當它是素數? –
2和1?我最多得到2和3 - 三個素數或更多給予無限循環。 – molbdnilo