一、时间复杂度O(N^3):
import time
def find_abc(max_bondary):
max_bondary += 1
for a in range(1, max_bondary):
for b in range(1, max_bondary):
for c in range(1, max_bondary):
if a + b + c == 1000 and a**2 + b**2 == c**2:
print("(a=%d, b=%d, c=%d)" % (a, b, c))
def main():
time_start = time.time()
find_abc(1000)
time_end = time.time()
print("time_cost=%f" % (time_end - time_start))
if __name__ == '__main__':
main()
二、时间复杂度O(N^2):
import time
def find_abc(max_bondary):
threshold_ac = max_bondary // 3
threshold_b = max_bondary // 2
for a in range(1, threshold_ac):
for b in range(a + 1, max_bondary):
c = 1000 - a - b
if a**2 + b**2 == c**2:
print("a=%d, b=%d, c=%d" % (a, b, c))
def main():
time_start = time.time()
find_abc(1000)
time_end = time.time()
cost_time = time_end - time_start
print("cost_time = %s" % cost_time)
if __name__ == '__main__':
main()
三、时间复杂度O(NlogN):
"""
二分法解决a+b+c=1000, a^2+b^2=c^2, a,b,c为正整数问题
分析:
a显然不等于b,如果a等于b,则c不能为整数;
为了避免重复,比如a和b交换位置的情况,不妨考虑a<b<c;
则可以知道a<1000/3, c>1000/3, b<1000/2;
"""
import time
def find_abc(max_bondary):
threshold_a = max_bondary // 3
threshold_b = max_bondary // 2
for a in range(1, threshold_a):
b_high = threshold_b
b_low = a + 1
while True:
b = (b_low + b_high) // 2
c = max_bondary - a - b
if a**2 + b**2 == c**2:
print("a=%d, b=%d, c=%d" % (a, b, c))
break
elif a**2 + b**2 > c**2:
b_high = b
elif a**2 + b**2 < c**2:
b_low = b + 1
# print("b_high - b_low = %d" % (b_high - b_low))
b_range = b_high - b_low
if b_range == 0:
# print("%d - %d = %d" % (b_high, b_low, b_high - b_low))
break
# print("="*10)
def main():
time_start = time.time()
find_abc(1000)
time_end = time.time()
time_cost = time_end - time_start
print("time_cost=%f" % time_cost)
if __name__ == '__main__':
main()