Project Euler #9: Special Pythagorean triplet

Question

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

Answer : 31875000

Hacker Rank Problem

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();

        for (int a0 = 0; a0 < t; a0++) {
            int n = in.nextInt();
            int result = -1;

            for (int a = 1; a <= n / 3; a++) {
                int c = (a * a / (2 * n - 2 * a)) + n / 2 - a / 2;
                int b = n - a - c;

                if (a * a + b * b == c * c && a < b && b < c) {
                    result = a * b * c;
                }
            }
            System.out.println(result);
        }
    }
}

Comments

Popular Posts