. A Pythagorean triplet is a set of three natural numbers, 0 < a < b < c, for which, a² + b² = c². For example, 3² + 4² = 9 + 16 = 25 = 5², so (3,4,5) is a Pythagorean triplet. Write a function void pyTriplet(int n). The function should print all Pythagorean triplets for which a + b + c = n. It should run in time O(n²)
时间: 2024-04-10 14:33:18 浏览: 30
Sure, I can help you with that. Here's an implementation of the `pyTriplet` function in C++ that prints all Pythagorean triplets for which a + b + c = n and runs in O(n²) time complexity:
```cpp
#include <iostream>
void pyTriplet(int n) {
for (int a = 1; a < n; a++) {
for (int b = a + 1; b < n; b++) {
int c = n - a - b;
if (c > 0 && a * a + b * b == c * c) {
std::cout << "(" << a << "," << b << "," << c << ")" << std::endl;
}
}
}
}
```
In this code, we use two nested loops to generate all possible values of `a` and `b`. We calculate `c` as the difference between `n`, `a`, and `b`. Then, we check if `c` is positive and if `a² + b² = c²`. If the conditions are met, we print the triplet `(a, b, c)`. Note that this implementation assumes that `n` is greater than 2.
You can call this function from your main program like this:
```cpp
int main() {
int n = 12; // example value of n
pyTriplet(n);
return 0;
}
```
This will print all Pythagorean triplets for `n = 12` that satisfy the condition `a + b + c = n`.
I hope this helps! Let me know if you have any further questions.