找出满足a+b+c=n(n为正整数)的所有毕达哥拉斯元组(a,b,c)【python实现,时间复杂度优化】

一、时间复杂度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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值