A square triple (a,b,c)
is a triple where a
, b
, and c
are integers and a2 + b2 = c2
.
Given an integer n
, return the number of square triples such that 1 <= a, b, c <= n
.
Example 1:
Input: n = 5 Output: 2 Explanation: The square triples are (3,4,5) and (4,3,5).
Example 2:
Input: n = 10 Output: 4 Explanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).
Constraints:
1 <= n <= 250
这题是给了一个数字n,要求直角三角形的三条边,最长边不超过n的数字组合的个数。注意读题,不是求第三边为n,而是最多为n哦。
就,brute force吧,意义不是太大。
class Solution {
public int countTriples(int n) {
int result = 0;
for (int i = 1; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int sum = i * i + j * j;
int k = (int) Math.sqrt(sum);
if (k * k == sum && k <= n) { // k <= n is given in description
result += 2;
}
}
}
return result;
}
}