【发布时间】:2016-03-25 20:48:37
【问题描述】:
我需要使用埃拉托色尼筛法找出从 2 到 n 的所有素数。我查看了 Wikipedia(Sieve of Eratosthenes) 以了解 Eratosthenes 的筛子是什么,它给了我这个伪代码:
Input: an integer n > 1
Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n:
if A[i] is true:
for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n :
A[j] := false
Output: all i such that A[i] is true.
所以我使用它并将其翻译成 C++。对我来说看起来不错,但我有几个错误。首先,如果我在 n 中输入 2 或 3,它会说:
terminate called after throwing an instance of 'Range_error'
what(): Range_error: 2
此外,每当我输入 100 或其他任何值(4、234、149、22 等)时,它都会接受 n 的输入,并且不执行任何操作。这是我的 C++ 翻译:
#include "std_lib_facilities.h"
int main()
{
/* this program will take in an input 'n' as the maximum value. Then it will calculate
all the prime numbers between 2 and n. It follows the Sieve of Eratosthenes with
the algorithms from Wikipedia's pseudocode translated by me into C++*/
int n;
cin >> n;
vector<string>A;
for(int i = 2; i <= n; ++i) // fills the whole table with "true" from 0 to n-2
A.push_back("true");
for(int i = 2; i <= sqrt(n); ++i)
{
i -= 2; // because I built the vector from 0 to n-2, i need to reflect that here.
if(A[i] == "true")
{
for(int j = pow(i, 2); j <= n; j += i)
{
A[j] = "false";
}
}
}
//print the prime numbers
for(int i = 2; i <= n; ++i)
{
if(A[i] == "true")
cout << i << '\n';
}
return 0;
}
【问题讨论】:
-
你想用那个 i -= 2 做什么?
-
你也需要在最后一个循环中调整
i。 -
单步调试代码时调试器会告诉你什么?
-
你为什么使用字符串向量而不是布尔向量(或最坏情况下的 int)?比较两个布尔值或整数比比较两个字符串要容易得多。
-
@Martze C++ 向量的索引从 0 到 n 对吗?但我从 2 开始。所以我将 'i' 向下移动 2 以便它与 0 索引相对应
标签: c++