直接用python代码的形式来看
# 问题
# a + b + c = 1000
# a*a + b*b = c*c
# 求 a b c
在以上问题求解的基础上,在此实现了三种算法,实现代码和输出结果以及算法复杂度T如下所示:
方法一
import time
# 方法一
start_time = time.time()
for a in range(0,1001):
for b in range(0, 1001):
for c in range(0, 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('method_1 cost time is : %d s'%(end_time-start_time))
print('finished method 1 ')
输出结果
a, b, c: 0 500 500
a, b, c: 200 375 425
a, b, c: 375 200 425
a, b, c: 500 0 500
method_1 cost time is : 132s
finished method 1
可以看出消耗时间上有132秒,method 1 时间复杂度为 T(n) = O(n^3)
方法二
# 方法二
start_time = time.time_ns()
for a in range (0,1001):
for b in range (0,1001):
if a**2 + b**2 ==(1000-a-b)**2:
print('a, b, c: %d %d %d ' % (a, b, 1000-a-b))
end_time = time.time_ns()
print('method_2 cost time is : %d ns'%(end_time-start_time))
print('finished method 2')
输出结果为如下所示
a, b, c: 0 500 500
a, b, c: 200 375 425
a, b, c: 375 200 425
a, b, c: 500 0 500
method_2 cost time is : 910669000 ns
注意:1s = 1 000 000 000 ns, method_2 cost time is : 910 669 000ns,意味着不到1s
同时 method_2 时间复杂度 T(n) = O(n^2)
方法三
# 方法三
start_time = time.time_ns()
c = [print(a,b,(1000-a-b )) for a in range(0,1001) for b in range(0,1001) if a**2+b**2 == (1000-a-b)**2 ]
end_time = time.time_ns()
print('method_3 cost time is : %d ns'%(end_time-start_time))
print('finished method 3')
输出结果如下所示
0 500 500
200 375 425
375 200 425
500 0 500
method_3 cost time is : 820679000 ns
finished method 3
可以看出 method_3 cost time is : 839 676 000ns,方法三比方法二略快一点
方法三的时间复杂度 T (n)= O(n^2),方法二和方法三 的时间复杂度是一样的
目前为止就想到这三种算法,mark
参考自https://www.bilibili.com/video/av46256220?from=search&seid=3284016986363356908