繁体   English   中英

C++ 寻找第n个素数

[英]C++ Finding the nth prime number

我试图找到第 n 个素数。 例如:输入1-结果2,输入2-结果3,输入3-结果5...

我的 isprime function 目前可以工作,但我无法弄清楚,一定有问题,请帮忙,谢谢:)

/*
      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 function:

  • 小于 2 的数字不会是素数,因此请先拒绝它们。
bool isPrime(int n) {
    if (n < 2) return false; // add this line
    bool answer = true;
    for (int i = 2; i < n; i++) {
        if (n % i == 0) {
            answer = false;
        }
    }
    return answer;
}

main改进function:

  • 仅当找到素数时才增加计数器。
  • 计算找到的素数,然后检查总数。
  • 检查数字,而不是计数器,是否是素数。
int main() {
    int userInput;
    cout<<"Please indicate which prime number do you want to see: ";
    cin>>userInput;

    for(int i=0, counter=0;counter<=userInput;i++){ // note: the global "counter" is shadowed here
        if(isPrime(i)){
            counter++;
            if(counter==userInput){
                cout<<counter<<"th prime number is : "<<i<<endl;
            }
        }
    }

    return 0;
}

感谢@MikeCAT

我将我的 isPrime function 更改为小于 2 的数字,

bool isPrime(int n) {
    bool answer = true;
    if(n<2){
        answer=false;
        return answer;
    }
    if(n>=2){
        for (int i = 2; i < n; i++) {
            if (n % i == 0) {
                answer = false;
                return answer;
        }
    }
    return answer;
    }
}

我还制作了 nthPrime 一个 function,

int nthPrime(int n){
    double i;
    for(i=2;counter<n;i++){
        if(isPrime(i)){
            counter++;
        }
    }
    return i-1;
}

为了显示结果,我使用了以下代码:

int userInput;
    cout<<"Please indicate which prime number do you want to see: ";
    cin>>userInput;

    cout<<counter<<"th prime number is : "<<nthPrime(userInput);
    return 0;

Output 例子:请注明你想看哪个素数: 5第5个素数是:11

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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