当我输入10 5000000之类的大数字时,为什么这个程序会崩溃?
#include <iostream>
using namespace std;
bool is_prime(int num , int cnt = -1){
if(cnt == -1)
cnt = num-1;
if(num <= 1)
return false;
if(cnt == 1)
return true;
if(num % cnt == 0)
return false;
return is_prime(num , cnt-1);
}
int count_primes(int start , int end){
if(start>end)
return 0;
if(is_prime(start))
return 1 + count_primes(start+1 , end);
else
return 0 + count_primes(start+1 , end);
}
int main()
{
cout<<count_primes(10 , 200);
return 0;
}
当我传递到功能时,为什么这个程序会崩溃 count_primes的参数像10和5000000。
当我通过10和50这样的参数时,它效果很好。
#include <iostream>
using namespace std;
bool is_prime(int num , int cnt = -1){
if(cnt == -1)
cnt = num-1;
if(num <= 1)
return false;
if(cnt == 1)
return true;
if(num % cnt == 0)
return false;
return is_prime(num , cnt-1);
}
int count_primes(int start , int end){
if(start>end)
return 0;
if(is_prime(start))
return 1 + count_primes(start+1 , end);
else
return 0 + count_primes(start+1 , end);
}
int main()
{
cout<<count_primes(10 , 200);
return 0;
}
why does this program crash when I pass to the function
count_primes arguments like 10 and 5000000.
when I pass arguments like 10 and 50 it works well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很高兴您尝试以功能性的方式解决它。您可以在两个点上进行改进:
count_primes()
中的所有返回语句都应该看起来像<代码>返回count_primes(...); 。为了实现这一目标,您可能需要引入其他累加器参数,在这种情况下,只有acc
。is_prime()
返回布尔值,因此您可以将其添加到累加器中,而无需使用IF。 SETnum
在is_prime()
tosqrt(num)
中的初始值。另外,使用-O3
和新标准(可能是C ++ 20)编译。我的计算机上适用于10、5000000的代码看起来像:
It is nice that you try to solve it in a functional manner. There are two points where you can improve it:
count_primes()
should look likereturn count_primes(...);
. To achieve this, you might need to introduce additional accumulator parameter(s), in this case just anacc
.is_prime()
returns a boolean, so you can add it to the accumulator, no need for if-statement. Setnum
's initial value inis_prime()
tosqrt(num)
. Also, compile with-O3
and newer standards (C++20 possibly).The code that works for 10, 5000000 on my machine looks like: