Eratosthenes C ++的筛选 - 内存范围错误

时间:2018-04-01 16:29:25

标签: c++ vector primes sieve-of-eratosthenes

我正在使用这个简单的代码来使用Sieve,但是有一个错误会阻止程序编译。您可以在下面找到代码:

// sieve_of_erathosthenes.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "../../Library/std_lib_facilities.h"

int main()
{
    // Create a boolean array "prime[0..n]" and initialize
    // all entries it as true. A value in prime[i] will
    // finally be false if i is Not a prime, else true.
    int n = 30;
    vector<int>prime;

    for (size_t i = 0; i < n; i++) {
        prime.push_back(true);
    }

    for (int p = 2; p*p <= n; p++)
    {
        // If prime[p] is not changed, then it is a prime
        if (prime[p] == true)
        {
            // Update all multiples of p
            for (int j = p * 2; j <= n; j += p)
                prime[j] = false;
        }
    }

    cout << "Following are the prime numbers smaller than or equal to " << n << '\n';

    // Print all prime numbers
    for (int p = 2; p <= n; p++)
        if (prime[p])
            cout << p << " ";

    return 0;
}

错误是: sieve_of_erathosthenes.exe中0x772308F2处的未处理异常:Microsoft C ++异常:内存位置0x004FF670的Range_error。

我是新生,我​​很难翻译调试器错误... 谢谢,伙计们!

1 个答案:

答案 0 :(得分:1)

for循环中,终止条件应为p<n,因为您的向量大小为n,向量为0索引。

因此,访问prime[n]超出范围。这就是错误的原因。