Leetcode 1925. Count Square Sum Triples
Given an integer n, return the number of square sum triples such that 1 <= a, b, c <= n and a^2 + b^2 = c^2.
A square sum triple (a,b,c) is a set of three positive integers that satisfy the above condition.
n? (Typically, knowing the constraints can help in optimizing the solution if required.)a, b, and c distinct?Let’s assume n can be moderately large based on typical problem constraints (e.g., 1 ≤ n ≤ 250 according to Leetcode standard constraints). Moreover, a, b, and c are distinct positive integers constrained by the range [1, n].
(a, b, c) where 1 <= a, b, c <= n.a^2 + b^2 == c^2.a and b.(a, b), compute c = sqrt(a^2 + b^2).c is an integer and within the range [1, n].O(n^2 * sqrt(n)) because for each pair (a, b), computing sqrt and checking the conditions will take constant time.#include <iostream>
#include <cmath> // for sqrt
using namespace std;
class Solution {
public:
int countSquareSumTriples(int n) {
int count = 0;
for (int a = 1; a <= n; ++a) {
for (int b = 1; b <= n; ++b) {
int cSquared = a * a + b * b;
int c = sqrt(cSquared);
if (c <= n && c * c == cSquared) {
count++;
}
}
}
return count;
}
};
int main() {
Solution solution;
int n = 10; // Example input
int result = solution.countSquareSumTriples(n);
cout << "Number of square sum triples: " << result << endl;
return 0;
}
n times.n times for each value of a, hence n * n in total.O(1).c: Constant time, O(1).Hence, the overall time complexity is O(n^2 * sqrt(n)) due to the computational cost and validation within the nested loops.
This solution explores all combinations and checks the conditions efficiently within polynomial time complexity constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?