#include <iostream>
#include <time.h>
using namespace std;
int main()
{
const int number = 1000000;
//Chain Vars-------------------
int chainLength = 0;
int startingNumber = 0;
int chain = 0;
int n = 0;
//----------------------------
// start Time-----------------
clock_t startTime = clock();
double duration;
//---------------------------
//Cache-----------------------------
int* cache = new int[number+1];
for (int i = 0; i < number+1; i++)
{
cache[i] = -1;
}
cache[1] = 1;
//---------------------------------
for (int i = 2; i <= 1000000; i++)
{
n = i;
chain = 0;
while (n != 1 && n >= i)
{
chain++;
if ((n % 2) == 0)
{
n = n/2;
}
else
{
n = n * 3 + 1;
}
}
//Store the chain length in cache
cache[i] = chain + cache[n];
//-------------------------------
if (cache[i] > chainLength)
{
chainLength = cache[i];
startingNumber = i;
}
}
//-----------------------------------------------------------------------------------------------
duration = ((clock() - startTime)/(double)CLOCKS_PER_SEC);
cout << "Starting Number is: " << startingNumber << " with a length of: " << chainLength << endl;
cout << "Duration = " << duration << endl;
//-----------------------------------------------------------------------------------------------
getchar();
return 0;
}
所以我的錯誤發生在第54行,並說我沒有權限訪問這個內存。在C#中相同的代碼工作得很好。爲什麼我不能在C++中使用這段代碼?
Pastebin:糟糕 - 在SO上發佈代碼:很好。發佈所有代碼:錯誤 - 發佈與問題相關的代碼:很好 –
*在c#中的相同代碼工作得很好。* - ** C#不是C++ ** – PaulMcKenzie
關閉一個錯誤。數組的索引從零開始,而不是從1開始。如果它在C#中起作用,那麼您很幸運 - 即使它看起來適用於您選擇的測試用例,C#中的代碼也會有缺陷。 – Peter