1 minute read

Problem Statement

leetcode problem link

My Solution [Accepted]

public class Solution {
    public int CountTriples(int n) {
        var res = new HashSet<Tuple<int, int, int>>();
        for (int i = 1; i < n; i++) {
            var a = i;
            var b = 0;
            for (int j = i + 1; j < n; j++) {
                b = j;
                var c = Math.Sqrt(a * a + b * b);
                if (c <= n && c != a && c != b && c % 1 == 0)
                {
                    res.Add(new Tuple<int, int, int>(a, b, (int)c));
                }
            }
            for (int j = i - 1; j >= 0; j--) {
                b = j;
                var c = Math.Sqrt(a * a + b * b);
                if (c <= n && c != a && c != b && c % 1 == 0)
                {
                    res.Add(new Tuple<int, int, int>(a, b, (int)c));
                }
            }
        }

        return res.Count;
    }
}

Editorial

public class Solution {
    public int CountTriples(int n) {
        int res = 0;
        // enumerate a and b
        for (int a = 1; a <= n; ++a) {
            for (int b = 1; b <= n; ++b) {
                // determine if it meets the requirements
                int c = (int)Math.Sqrt(a * a + b * b + 1.0);
                if (c <= n && c * c == a * a + b * b) {
                    ++res;
                }
            }
        }
        return res;
    }
}
from math import sqrt


class Solution:
    def countTriples(self, n: int) -> int:
        res = 0
        # enumerate a and b
        for a in range(1, n + 1):
            for b in range(1, n + 1):
                # determine if it meets the requirements
                c = int(sqrt(a**2 + b**2 + 1))
                if c <= n and c**2 == a**2 + b**2:
                    res += 1
        return res