WinForms c ++ task:

Write a program that finds all right triangles (the lengths of the sides are expressed by natural numbers), the area of ​​which does not exceed the given number S.

The difficulty in writing the algorithm for finding a right triangle, the enumeration of all the numbers in a row is apparently incorrect. I do not understand how to implement this cycle?

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { int a = 0; int b = 0; int s, k; s = Convert::ToInt64(textBox1->Text); k = 0;// количество прямоугольных треугольников for (int a = 1; a <= 100; a++) { for (int b = 1; b <= 100; b++) { if (0.5 * a * b < s) { k++; // если площадь не превышает S, увеличиваем k на 1 } } } textBox2->Text = Convert::ToString(k) // выводим k } 
  • Should all three sides of a triangle be intact? Or just the legs? - Harry
  • @Harry all three sides must be whole - propane67
  • Then simply consider all Pythagorean triples , checking the corresponding pairs (m, n), taking into account the fact that (m^2-n^2)mn <= S - Harry
  • Yes, thanks, I figured it out - propane67

1 answer 1

Here, written on my knee, without the slightest attempt to optimize the code to search for all the triangles with an area up to a given one.

 unsigned int S; cin >> S; for(unsigned int n = 1;n*(n+1)*(2*n+1) <= S;++n) { for(unsigned int m = n+1; (m*mn*n)*m*n<=S; ++m) { if (m%2 == n%2 || gcd(m,n) > 1) continue; unsigned int a = m*m - n*n; unsigned int b = 2*m*n; unsigned int c = m*m+n*n; unsigned int s = a*b/2; for(unsigned int k = 1; s*k*k <= S; ++k) cout << setw(4) << k*a << " " << setw(4) << k*b << " " << setw(4) << k*c << " " << setw(4) << k*k*s << endl; } } 
  • Is it possible to replace gcd with anything? Vs does not support him - propane67
  • Just VC ++ 2017 fully supports it. Well, write for yourself - this is 2 lines ... - Harry
  • Can you explain what these lines do? for (unsigned int n = 1; n * (n + 1) * (2 * n + 1) <= S; ++ n) {for (unsigned int m = n + 1; (m m-n n) * m * n <= S; ++ m) What are they for and what are they finding? - propane67
  • Just cycle through all possible options. In the loop header, the maximum value of n at which the area may not be exceeded; below, in the second cycle - the second check, now by m. - Harry
  • And where does n * (n + 1) * (2 * n + 1) come from? - propane67