LeetCode 1925. Count Square Sum Triples

该问题要求找出所有边长a,b,c(a<=b<=c)为整数,且满足a^2+b^2=c^2的直角三角形,其中1<=a,b,c<=n。提供的解决方案使用暴力枚举方法,遍历所有可能的a和b值,然后计算c的平方根k,如果k*k等于sum并且k<=n,则增加结果计数。
摘要由CSDN通过智能技术生成

square triple (a,b,c) is a triple where ab, 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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值