Project Euler #9: Special Pythagorean triplet

  • + 0 comments
    import java.util.*;
    
    public class Solution {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int t = in.nextInt();
            for (int i=0; i<t; i++) {
                long n = in.nextLong();
                System.out.println(pythagoreanTriplet(n));
            }
            in.close();
        }
        
        public static long pythagoreanTriplet(long n) {
            long result = -1;
    
            for (long k=2; k<=n/3; k++) {
                long j = ((n*n)-(2*n*k)) / (2*(n-k));
                long i = n - k - j;
    
                if (k*k + j*j == i*i) {
                    result = Math.max(result, k*j*i);
                }
            }
    
            return result;
        }
    }