📌  相关文章
📜  计算给定周长下可能的直角三角形数量

📅  最后修改于: 2021-06-26 00:50:23             🧑  作者: Mango

给定周长P,任务是找到周长等于p的直角三角形的数量。
例子:

Input: P = 12
Output: number of right triangles = 1 
The only right angle possible is with sides 
hypotenuse = 5, perpendicular = 4 and base = 3. 

Input: p = 840
Output: number of right triangles = 8

因此,目的是找到满足方程a + b + c = p和a 2 + b 2 = c 2的解的数量
天真的方法是对a(1到p / 2)和b(a + 1到p / 3)运行两个循环,然后使c = pab,如果a*a + b*b == c*c   。这将需要O(p^{2})   时间。
很少的代数运算可以找到一种有效的方法:

由于a + c> b或,p – b> b或b

下面是上述方法的实现。

C++
// C++ program to find the number of
// right triangles with given perimeter
#include
using namespace std;
 
// Function to return the count
int countTriangles(int p)
{
  // making a list to store (a, b) pairs
  vector> store;
 
  // no triangle if p is odd
  if (p % 2 != 0)
    return 0;
  else
  {
    int count = 1;
 
    for(int b = 1; b < p / 2; b++)
    {
      float a = (float)p / 2.0f * ((float)((float)p -
                                           2.0 * (float)b) /
                                   ((float)p - (float)b));
 
      int inta = (int)(a);
 
      if (a == inta)
      {
        // make (a, b) pair in sorted order
        pair ab;
 
        if(intaPython3
# python program to find the number of
# right triangles with given perimeter
 
# Function to return the count
def countTriangles(p):
     
    # making a list to store (a, b) pairs
    store =[]
 
    # no triangle if p is odd
    if p % 2 != 0 : return 0
    else :
        count = 0
        for b in range(1, p // 2):
 
            a = p / 2 * ((p - 2 * b) / (p - b))
            inta = int(a)
            if (a == inta ):
 
                # make (a, b) pair in sorted order
                ab = tuple(sorted((inta, b)))
 
                # check to avoid duplicates
                if ab not in store :
                    count += 1
                    # store the new pair
                    store.append(ab)
        return count
 
# Driver Code
p = 840
print("number of right triangles = "+str(countTriangles(p)))


输出:
number of right triangles = 8

时间复杂度: O(P)

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。