【发布时间】:2020-07-30 05:32:12
【问题描述】:
我开始学习 c++,并且正在应对 Project Euler 挑战,#7 要求您找到给定范围内的所有素数。经过在线研究,我决定尝试使用Sieve of Erastothenes,但是使用我设置的代码,当我要求 2 个素数和 (2, 4, 5, 5) 时,我目前得到奇怪的值,例如 )2, 0)当我输入 5.
#include <iostream>
#include <vector>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
int main(){
int end_point;
cout << "how many prime numbers would you like to find?\n";
cin >> end_point;
//creates a vector to store all values, that will eventually be whittled down to primes
vector<int> primes = {2};
//adds all numbers between 2 and chosen end point to the vector
for (int i = 3; i <= end_point; i++){
primes.push_back(i);
}
for (int i = 0; i < end_point; i++){
//starts at the first value (always 2), and feeds it into the next for loop
//once the next loop is done, it moves on to the next value in the loop and feeds that in
primes[i];
//looks at values in the vector, starting with the next value in the vector
for (unsigned int j = i+1; j < primes.size(); j++){
//checks if the value at [j] is divisible by the value at [i]
//if it is, this deletes it from the vecotr
//if not, it moves on to the next value in the vector
if(primes[j] % primes[i] == 0){
primes.erase (primes.begin() + (j-1));
}
else{}
}
//prints out all of the primes in the specified range
cout << "Primes are: ";
for (unsigned int k = 0; k <= primes.size(); k++){
cout << primes[k] << ", ";
}
}
}
【问题讨论】:
-
这里有很多错误,例如您使用
end_point就好像它是您的primes向量的大小,但事实并非如此。如果您将primes声明为布尔向量,您会发现这更容易(并且您的代码也将更有效率)。因此,如果n已被证明不是素数,则primes[n]为假。这种方法意味着您不必调整primes向量的大小,这将使您的代码不仅更简单而且更高效。 -
#include <bits/stdc++.h>- 不要永远包含该标题。它是一个内部实现特定的头文件,不打算包含在内,也不能与其他编译器一起使用。另见Why should I not #include <bits/stdc++.h>? -
声明
primes[i];应该做什么?因为它没有。 -
对于欧拉计划,我将素数存储在
std::set<long int>中。 ;-) -
@MarquisofLorne,我打算让 primes[i] 跟踪我们在向量中的位置,例如,第一次迭代它应该找到 i = 0 处的值,即 2,并且检查 2 的倍数,然后在我迭代时检查 i = 1,即 3。至少,这就是我的意图。导致它什么也不做的错误在哪里?