【发布时间】:2019-10-13 13:54:21
【问题描述】:
我试图找到第 n 个素数。 例如:输入1-结果2,输入2-结果3,输入3-结果5...
我的isprime函数目前可以正常工作,但我想不通,一定有问题,请帮忙,谢谢:)
/*
Finding the nth Prime Number
Yasin OSMAN
*/
//Including Libraries
#include <iostream>
using namespace std;
//Defining a global counter
int counter = 0;
/*
Defining Functions
*/
//isPrime Function (returns true if the given number is prime)
bool isPrime(int n) {
bool answer = true;
for (int i = 2; i < n; i++) {
if (n % i == 0) {
answer = false;
}
}
return answer;
}
int main() {
int userInput;
cout<<"Please indicate which prime number do you want to see: ";
cin>>userInput;
for(int i=0;i<=userInput;i++){
if(isPrime(counter)){
if(counter==userInput){
cout<<counter<<"th prime number is : "<<i<<endl;
}
counter++;
}
counter++;
}
return 0;
}
【问题讨论】:
-
这个
isPrime函数会错误地将小于等于1的数字判断为素数。 -
在
isPrime函数中,当你执行answer = false赋值时,为什么还要继续循环呢?为什么不直接return false? -
你应该在
main函数的循环中增加counter两次吗? -
是的,我应该这样做,我在 answer=false 之后返回 false; @Someprogrammerdude