C++实现Eratosthenes筛法算法中的运行时错误可能的原因是什么?

huangapple go评论53阅读模式
英文:

What could be causing a runtime error in my C++ implementation of the Sieve of Eratosthenes algorithm?

问题

运行时出错的原因可能是因为您的代码中存在一些问题,需要进行修复。以下是修复后的代码:

#include <bits/stdc++.h>
using namespace std;

vector<long long> prima;

void SieveOfEratosthenes() {
    bool prime[1000006];
    memset(prime, true, sizeof(prime));

    for (long long int p = 2; p <= 1000000; p++) {
        if (prime

== true) { prima.push_back(p); for (long long int i = p * p; i <= 1000000; i += p) { prime[i] = false; } } } } int main() { long t; cin >> t; SieveOfEratosthenes(); while (t--) { long long int k; cin >> k; cout << prima[k - 1] << endl; } return 0; }

这个修复后的代码应该能够在在线编译器中正常运行,输出第 k 个素数。

英文:

WHY RUN TIME ERROR?..please help
i am trying to output the ith prime number but i keep gettng run time error.i can run the code in an offline compiler but not in a online compiler

#include&lt;bits/stdc++.h&gt;
using namespace std;

vector&lt;long long&gt;prima;
long long int SieveOfEratosthenes(){
    bool prime[1000006];
    for (long long int p = 2; p &lt;= 1000000; p++) {
        if (prime

==false){ prima.push_back(p); for (long long int i = p * p; i &lt;= 1000000; i += p){ prime[i] = true; } } } } int main(){ long t; cin&gt;&gt;t; SieveOfEratosthenes(); while(t--){ long long int k; cin&gt;&gt;k; cout&lt;&lt;prima[k-1]; } return 0; }

答案1

得分: 1

这个声明

    bool prime[1000006];

会使`prime`数组的值变为未定义,包括可能导致未定义行为的陷阱值。即使你修复了这个问题,数组如此庞大也会有栈溢出的风险。

所以只需将上述行替换为:

    std::vector<bool> prime(1000006);

除了在文件顶部添加`#include <vector>`之外,其他所有内容保持不变。
英文:

This declaration

bool prime[1000006];

Leaves the values in prime undefined including trap values that will cause undefined behavior. Even if you fix that, it risks stack overflow for being so large.

So just replace the above line with:

std::vector&lt;bool&gt; prime(1000006);

Aside from a #include &lt;vector&gt; at the top of the file, everything else remains the same.

huangapple
  • 本文由 发表于 2023年6月1日 12:52:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76378753.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定