
import time
start_time = time.time()
for a in range(1,1001):
for b in range(1,1001):
for c in range(1,1001):
if a+b+c == 1000 and a**2 + b**2 == c**2:
print("a, b, c:%d,%d,%d"%(a,b,c))
end_time = time.time()
print("time:%d"%(end_time-start_time))
执行结果如下:
E:\Anaconda\envs\Pytorch\python.exe E:/PycharmSoftware/python/20201017_file1.py
a, b, c:200,375,425
a, b, c:375,200,425
time:132s
Process finished with exit code 0
同样的问题,让C++来做,大跌眼镜
#include<iostream>
#include <windows.h>
using namespace std;
int main(void)
{
double start = GetTickCount();
Sleep(1000);
int i, j, k;
for (i = 0; i <= 1000; i++)
{
for (j = 0; j <= 1000; j++)
{
for (k = 0; k <= 1000; k++)
{
if ((i + j + k == 1000) && (i*i + j*j == k*k))
{
cout << "i = "<< i << " " << "j = " <<j<< " " << " k = " << k << endl;
}
}
}
}
double end = GetTickCount();
cout << "GetTickCount:" << (end - start)/1000 << endl;
system("pause");
return 0;
}
执行结果:
i = 0 j = 500 k = 500
i = 200 j = 375 k = 425
i = 375 j = 200 k = 425
i = 500 j = 0 k = 500
GetTickCount:2.891s
请按任意键继续. . .

算法优化,因为a + b + c = 1000,所以c = 1000 - a - b
这时就不用试验这么多次了
如下所示:
import time
start_time = time.time()
for a in range(0,1001):
for b in range(0,1001):
# for c in range(1,1001):
c = 1000 - a - b
if a**2 + b**2 == c**2:
print("a, b, c:%d,%d,%d"%(a,b,c))
end_time = time.time()
print("time:%d"%(end_time-start_time))
效率提高了很多倍

但靠时间是不能进行比较的,还要看环境而定
于是提出里时间复杂度的概念
不同的机器基本运算数量大体相同

for a in range(1,1001):
for b in range(1,1001):
for c in range(1,1001):
if a+b+c == 1000 and a2 + b2 == c**2:
print(“a, b, c:%d,%d,%d”%(a,b,c))
时间复杂度:
T(n) = N * N * N * 2
= 1000 * 1000 * 1000 * 2
武汉:20201017 晚10点30分 (未完待续…)
&spm=1001.2101.3001.5002&articleId=109138849&d=1&t=3&u=1a4a484c2e084a51a3d523fcd41fd007)

被折叠的 条评论
为什么被折叠?



