python演算法(列舉法):如果a + b + c = 1000(a, b, c均為非負整數),求滿足a^2 + b^2 = c^2的所有可能的值。

Jerry_JD發表於2019-01-11

如果a + b + c = 1000(a, b, c均為非負整數),求滿足a^2 + b^2 = c^2的所有可能的值。

import time

def method():
    time_start = time.time()
    for a in range(1001):
        for b in range(1001):
            for c in range(1001):
                if a * a + b * b == c * c and a + b + c == 1000:
                    print('a = %d, b = %d, c = %d' % (a, b, c))
    time_end = time.time()
    print('總共耗時:%d' % (time_end - time_start))


def method_():
    time_start = time.time()
    for a in range(1001):
        for b in range(1001 - a):
            for c in range(1001):
                if a * a + b * b == c * c and a + b + c == 1000:
                    print('a = %d, b = %d, c = %d' % (a, b, c))
    time_end = time.time()
    print('總共耗時:%d' % (time_end - time_start))

def method_optimized():
    time_start = time.time()
    for a in range(1001):
        for b in range(1001):
            c = 1000 - a -b   # 減少時間複雜度
            if a * a + b * b == c * c:
                print('a = %d, b = %d, c = %d' % (a, b, c))
    time_end = time.time()
    print('總共耗時:%d' % (time_end - time_start))


if __name__ == '__main__':
    method()
    method_()
	method_optimized()

相關文章