如何打印给定范围内的直角三角形的周长和数量?

时间:2019-02-19 12:48:54

标签: c++ for-loop if-statement math.h pythagorean

问题需要用户输入两个值P和Q。然后程序将输出直角整数三角形的数目及其从P到Q的周长。 例如:

输入: 154180

输出:

154 1

156 1

160 1

168 3

176 1

180 3

我认为我需要找出P-Q范围内的勾股三元组,但是如何计算“直角三角形数”呢? 这是我的代码:

#include <iostream>
#include <math.h>
using namespace std;
int main() {
int P, Q, a, b, c, i = 0;
cin >> P >> Q;
for ( a = P; a <= Q; ++a)
{
   for ( b = a; b <= Q; ++b)
   {
      for ( c = b; b <= Q; ++c)
      {
         if ((pow(a, 2) + pow(b, 2)) == pow(c, 2) && a + b + c <= Q)
         {
             i +=1;
             cout << a + b + c << " " << i << endl;
             }
      }
    }
}
return 0;
}

超级谢谢!!

1 个答案:

答案 0 :(得分:0)

我们可以通过std::map计算具有特定周长的直角整数三角形,该周长为键,三角形的数量为值:

std::map<int, int> triangle_map;

接下来,使用通过翻转交换ab的三角形的对称性,可以将发现搜索限制为a<=b的情况。 但是,如果a==bc=sqrt(2)*a,则a不是整数。 因此,以下双循环搜索将很适合我们,并且可以找到所有目标三角形:

const int Qmax_a = (Q-1)/2; // 1 is the minimum value of c.

for (int a = 1; a <= Qmax_a; ++a)
{
    const int a_sqr = a*a;

    for (int b = a+1; b <= Q-a-1; ++b)
    {
        const int two_side_sqr = a_sqr + b*b;

        // possible candidate
        const int c = static_cast<int>(std::round(std::sqrt(two_side_sqr)));
        const int perimeter = (a+b+c);

        if((c*c == two_side_sqr) && (P <= perimeter) && (perimeter <= Q)){
            triangle_map[perimeter] += 1;
        }
    }
}

最后,我们可以从结果图获得所需的输出:

DEMO

for(const auto& p : triangle_map){
    std::cout << p.first << "," << p.second << std::endl;
}