我最初用Python写了一个小程序,但是运行速度非常慢,所以我转而使用了C++。尽管我之前在C#上编程经验丰富,但对于这种特定的语言还是没有经验,所以我选择了一个在线编辑器https://www.onlinegdb.com/online_c++_compiler。
我的C++代码如下:
clock_t start, end;
/* Recording the starting clock tick.*/
start = clock();
int R = 0;
int x = 0;
for (R = 6; R <= 10000; R = R + 2) {
int X_min = ceil(0.5 * sqrt(2) * R);
int N_pairs = 0;
for (x = X_min; x < R; x++) {
float y = sqrt(pow(R, 2) - pow(x, 2));
if (rint(y) == y) {
N_pairs = N_pairs + 1;
}
}
if (N_pairs >= 4) {
//cout << R << ", " << N_pairs;
//cout << "\n";
}
}
end = clock();
//Calculating total time taken by the program.
double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
cout << "Time taken by program is : " << time_taken;
cout << " sec " << endl;
//cout << "1" << "|" << "2" << "|" << "3 \n";
//cout << "4" << "|" << "5" << "|" << "6 \n";
//cout << "7" << "|" << "8" << "|" << "9 \n";
一切都很顺利,但是网页编辑器似乎有一个内置的最大时间限制,所以我决定把它移到Visual Studio。
我复制并粘贴了代码并运行了它:
- 网页编辑器花费0.272273秒完成了代码
- Visual Studio花费2.446秒运行了它。
我尝试将VS从2017版本更新到2019版本,但没有任何效果。
为什么VS运行代码需要这么长时间?如何解决这个问题?
sqrt(R*R - x*x)
来避免使用 pow(),确保目标为 x64。 - Hans Passant