英文:
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<bits/stdc++.h>
using namespace std;
vector<long long>prima;
long long int SieveOfEratosthenes(){
bool prime[1000006];
for (long long int p = 2; p <= 1000000; p++) {
if (prime==false){
prima.push_back(p);
for (long long int i = p * p; i <= 1000000; i += p){
prime[i] = true;
}
}
}
}
int main(){
long t;
cin>>t;
SieveOfEratosthenes();
while(t--){
long long int k;
cin>>k;
cout<<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<bool> prime(1000006);
Aside from a #include <vector>
at the top of the file, everything else remains the same.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论