Blue Bridge Cup Pythagorean Violence

Problem Description
  A set of three numbers is the Pythagorean natural numbers, a <b <c, to which three atoms form a triangle with three sides of a right triangle is possible to
  output all a + b + c <= 1000 number of Pythagorean
  a small first output ; The same as a, b is output first.
Output format
  Each row is a group of Pythagoras, separated by spaces
Sample output
For example, the first three rows of the result should be
3 4 5
5 12 13
6 8 10
Water question, but some thoughts are still very helpful to me.
My first version of the code looks like this.
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main() {
 4     for (int i = 1; i <= 1000; i++) {
 5         for (int j = 1; j <= 1000; j++) {
 6             for (int k = 1; k <= 1000; k++) {
 7                 if (i + j + k <= 1000 && i * i + j * j == k * k) {
 8                     cout << i << " " << j << " " << k << endl;
 9                 }
10             }
11         }
12     }
13     return 0;
14 }

Then the time complexity is 10 ^ 9.

Then see that the title requires a small output first, then b small output, then c small output.

Then it can be changed to this.

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main() {
 4     for (int i = 3; i <= 1000; i++) {
 5         for (int j = i + 1; j <= 1000; j++) {
 6             for (int k = j + 1; k <= 1000; k++) {
 7                 if (i + j + k <= 1000 && i * i + j * j == k * k) {
 8                     cout << i << " " << j << " " << k << endl;
 9                 }
10             }
11         }
12     }
13     return 0;
14 }

This ensures that the output of a is small, then the output of b is small, and then the output of c is small.

Then you can also subtract the extra operations, so the outermost layer can be changed to  for (int i = 3; i <= 333; i ++). Because 333 + 334 + 335 is greater than 1000. In the same way, the scope of the second layer can be modified, and the third layer cannot be changed significantly.

Then there is the final version of the code with less time complexity.

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main() {
 4     for (int i = 3; i <= 333; i++) {
 5         for (int j = i + 1; j <= 500; j++) {
 6             for (int k = j + 1; k <= 999; k++) {
 7                 if (i + j + k <= 1000 && i * i + j * j == k * k) {
 8                     cout << i << " " << j << " " << k << endl;
 9                 }
10             }
11         }
12     }
13     return 0;
14 }

Guess you like

Origin www.cnblogs.com/fx1998/p/12738119.html