- 第一次尝试
# 如果a+b+c=1000,且a^2+b^2=c^2(a,b,c为自然数),如何求出所有a,b,c可能的组合?
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("times:%d" % (end_time - start_time))
print("finished")
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/xinqi/PycharmProjects/test/test.py
a, b, c: 0, 500, 500
a, b, c: 200, 375, 425
a, b, c: 375, 200, 425
a, b, c: 500, 0, 500
times:185
finished
Process finished with exit code 0
- 第一次尝试的改进,如此一来时间缩短了许多
# 如果a+b+c=1000,且a^2+b^2=c^2(a,b,c为自然数),如何求出所有a,b,c可能的组合?
import time
start_time = time.time()
for a in range(0, 1001):
for b in range(0, 1001):
#因为c是可以从a和b得出的,所以c不需要再从0到1000遍历一边
c = 1000 - a - b
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("times:%d" % (end_time - start_time))
print("finished")
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/xinqi/PycharmProjects/test/test.py
a, b, c: 0, 500, 500
a, b, c: 200, 375, 425
a, b, c: 375, 200, 425
a, b, c: 500, 0, 500
times:1
finished
Process finished with exit code 0