1

The question need the user input two value, P and Q. The program then will output the number of right angle integer triangle as well as its perimeter from P to Q. For example:

Input: 154 180

Output:

154 1

156 1

160 1

168 3

176 1

180 3

I think i need to find out the Pythagorean Triples in the P-Q range, but how to count the " number of right-angled triangle " ? Here are my code :

#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;
}

Super Thanks !!

eulerisgod
  • 135
  • 6
  • BTW, `(a * a)` is more efficient than `pow(a,2)`. There will be conversion from int to float, then float to int when using `pow()`. The multiplication has no conversions and is often one processor instruction. – Thomas Matthews Feb 19 '19 at 15:10

1 Answers1

0

We can count the right angle integer triangles with a specific perimeter by std::map which has the perimeters as keys and the number of triangles as values:

std::map<int, int> triangle_map;

Next, using the symmetry of triangles of exchanging a and b with flipping, we can restrict our finding search into the case of a<=b. But if a==b then c=sqrt(2)*a which is not an integer when a is an integer. Therefore the following double-loop search would well work for us and can find all the target triangles:

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;
        }
    }
}

Finally, we can get the desired output from the resulted map:

DEMO

for(const auto& p : triangle_map){
    std::cout << p.first << "," << p.second << std::endl;
}
Hiroki
  • 2,780
  • 3
  • 12
  • 26