Pythagorean Triple Check

easy Programming Basics

Problem

Three positive numbers are given in any order. Print true if they can be the sides of a right triangle (the square of the longest side equals the sum of the squares of the other two). Otherwise print false.

Constraints

  • 1 <= side <= 10^6

Examples

Input

5 3 4

Output

true

Solutions

Best approachTime O(1)Space O(1)

Only the longest side can be the hypotenuse. Total squares minus the longest square gives the sum of the other two squares. The comparison needs no sorting.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Right triangle check.
 * Input   : Three sides.
 * Output  : true or false.
 * Approach: Longest side.
 * Time    : O(1)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static boolean solve(long a, long b, long m) {
        // Step 1: Find the longest side. Then the other two are the short sides.
        long longest = Math.max(a, Math.max(b, m));
        long sumOfSquares = a * a + b * b + m * m - longest * longest;
        // Step 2: The right-triangle rule: short1^2 + short2^2 = longest^2.
        return sumOfSquares == longest * longest;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long a = scanner.nextLong();
        long b = scanner.nextLong();
        long m = scanner.nextLong();
        System.out.println(solve(a, b, m));
    }
}
Hints (2)
  1. Which side can be the hypotenuse?
  2. Why is no sorting needed?