给定和的勾股三重态

2024-04-25 21:58:14 发布

您现在位置:Python中文网/ 问答频道 /正文

如果毕达哥拉斯三元组等于输入,下面的代码将打印它,但问题是,像90000这样的大数字需要很长时间才能回答。 如何优化以下代码? 1.≤ N≤ 9万

def pythagoreanTriplet(n):

    # Considering triplets in
    # sorted order. The value
    # of first element in sorted
    # triplet can be at-most n/3.
    for i in range(1, int(n / 3) + 1):

        # The value of second element
        # must be less than equal to n/2
        for j in range(i + 1,
                       int(n / 2) + 1):

            k = n - i - j
            if (i * i + j * j == k * k):
                print(i, ", ", j, ", ",
                      k, sep="")
                return

    print("Impossible")
# Driver Code
vorodi = int(input())
pythagoreanTriplet(vorodi)

Tags: ofthe代码inforvaluerangeelement
1条回答
网友
1楼 · 发布于 2024-04-25 21:58:14

您的source code对解决方案进行暴力搜索,因此速度很慢

更快的代码

def solve_pythagorean_triplets(n):
  " Solves for triplets whose sum equals n "
  solutions = []
  for a in range(1, n):
    denom = 2*(n-a)
    num = 2*a**2 + n**2 - 2*n*a
    if denom > 0 and num % denom == 0:
      c = num // denom
      b = n - a - c
      if b > a:
        solutions.append((a, b, c))

  return solutions

操作代码

修改了操作代码,使其返回所有解决方案,而不是打印第一个发现的用于比较性能的解决方案

def pythagoreanTriplet(n): 

    # Considering triplets in  
    # sorted order. The value  
    # of first element in sorted  
    # triplet can be at-most n/3. 
    results = []
    for i in range(1, int(n / 3) + 1):  

        # The value of second element  
        # must be less than equal to n/2 
        for j in range(i + 1,  
                       int(n / 2) + 1):  

            k = n - i - j 
            if (i * i + j * j == k * k):
                results.append((i, j, k))

    return results

定时

 n     pythagoreanTriplet (OP Code)     solve_pythagorean_triplets (new)
  900   0.084 seconds                       0.039 seconds
  5000  3.130 seconds                       0.012 seconds
  90000 Timed out after several minutes     0.430 seconds

解释

函数solve_pythagorean_triplets是一种O(n)算法,其工作原理如下

  1. 搜索:

    a^2 + b^2 = c^2 (triplet)
    a + b + c = n   (sum equals input)
    
  2. 通过搜索a(即迭代的固定值)求解。对于固定值,我们有两个方程和两个未知数(b,c):

    b + c = n - a
    c^2 - b^2 = a^2
    
  3. 解决办法是:

    denom = 2*(n-a)
    num = 2*a**2 + n**2 - 2*n*a
    if denom > 0 and num % denom == 0:
        c = num // denom
        b = n - a - c
        if b > a:
            (a, b, c) # is a solution
    
  4. 迭代一个范围(1,n)以获得不同的解决方案

相关问题 更多 >