0

我完成了一个素数生成程序。现在,我想测试所有素数所需的时间并将这些数字存储在一个数组中。我写了这段代码......

#include <iostream>
#include <ctime>
using namespace std;

int main ()
{


    int long MAX_NUM = 1000000;
    int long MAX_NUM_ARRAY = MAX_NUM+1;
    int long sieve_prime = 2;
    int long sieve_prime_constant = 0;
    int time_store = 0;
    int *Num_Array = new int[MAX_NUM_ARRAY];
    std::fill_n(Num_Array, MAX_NUM_ARRAY, 3);
    Num_Array [0] = 1;
    Num_Array [1] = 1;

while (time_store<=100)
{
    clock_t time1,time2;
    time1 = clock();
    while (sieve_prime_constant <= MAX_NUM_ARRAY)
    {
        if (Num_Array [sieve_prime_constant] == 1)  
        {

            sieve_prime_constant++;
        }
        else
        {
            Num_Array [sieve_prime_constant] = 0;  
            sieve_prime=sieve_prime_constant; 
             while (sieve_prime<=MAX_NUM_ARRAY - sieve_prime_constant)  
            {
                sieve_prime = sieve_prime + sieve_prime_constant;
                Num_Array [sieve_prime] = 1;
            }
            if (sieve_prime_constant <= MAX_NUM_ARRAY)
            {
                sieve_prime_constant++;
                sieve_prime = sieve_prime_constant;
            }
        }
    }
    time2 = clock();
    delete[] Num_Array;
    cout << "It took " << (float(time2 - time1)/(CLOCKS_PER_SEC)) << " seconds to    execute    this loop." << endl;
    cout << "This loop has already been executed " << time_store << " times." << endl;
    float Time_Array[100];
    Time_Array[time_store] = (float(time2 - time1)/(CLOCKS_PER_SEC));
    time_store++;
}


return 0;

}

当我运行它时,程序似乎经历了一次长循环然后崩溃。出了什么问题,我该如何解决?

4

1 回答 1

1

numArray在第一个循环结束时删除你,所以当你再次四处走动时引用 NULL ......

不知道你打算用这个delete[]语句做什么......但无论你打算做什么 - 要么在其他地方做,要么做其他事情,或者重新初始化数组,或者......你无疑可以从这里。

于 2013-02-10T21:36:04.977 回答