且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我用C ++编写了这段代码来打印第n个素数。如何通过递归编写此代码?

更新时间:2023-11-23 15:21:40

错误报告:初看起来我会说你的程序找不到第一个素数。



问题:你为什么要使用递归来查找数字是否为素数?

好吧它可以简化代码,但它是以牺牲PC资源为代价的,对于大量的数据,你可能会遇到堆栈溢出。

如果你非常仔细地编写递归代码,就有可能利用终端递归优化取决于编译器功能。



此外,您的程序远未优化,您使用非常天真的方法。如果你想优化代码,可以获得巨大的收益。


谷歌是你的朋友:递归素数 - Google搜索 [ ^ ]

#include<iostream>
using namespace std;
int main()
{
    int a,j=2,c=0;
    cin>>a;
    for(int i=2;i<(a*a);i++)
    {   for( j=2;j<i;j++)>
        {
            if(i%j==0)
                break;

        }
        if(i==j)
        {
            c++;
            if(c==a)
            {
                cout<<i;  return 0;
            }
        }
    }
    return 0;
}



What I have tried:

i have written this code to print the nth prime number and want to develop it through recursive function.

Bug report: On first look I would say that your program fail to find the first prime.

Question: why do you want to use recursion to find if a number is prime ?
Ok it may simplify the code, but it is at expense of PC resources, for large numbers you are at rick of stack overflow.
If you write the recursive code very carefully, it is possible to take advantage of the terminal recursion optimization depending on compiler capabilities.

Also your program is far from optimized, you use a very naive method. If you want to optimize the code, huge gains can be achieved.


Google is your friend: recursive prime - Google Search[^]