Reputation: 794
I have integers a, b and c.
Valid right angle means all the sides are positive integers, and they make a valid right angle triangle.
I'll then have to output the result (easy).
Full disclaimer: This is the course and assignment that I'm trying to finish
My attempt (Java):
// int a, b, c = 3, 4, 5;
// how do I even start checking if I'm not allowed to use "if / else"
// therefore not shown in code
int aSquare = a * a;
int bSquare = b * b;
int cSquare = c * c;
// *Im hoping they dont flag this as a conditional
System.out.println(
(aSquare == (bSquare + cSquare) || bSquare == (cSquare + aSquare)
|| cSquare == (aSquare + bSquare))
);
Upvotes: 3
Views: 366
Reputation: 3418
Based on the nature of the question, it is more meaningful to use assert
in case if the user inputted a negative number:
assert a > 0 && b > 0 && c > 0: "Sides can not be negative";
Also, you can use bitwise operators to extract sign of an integer:
// sign is 1 if i is zero, 0 if it is negative, 2 if it is positive
int sign = 1 + (i >> 31) - (-i >> 31);
Upvotes: 0
Reputation: 89224
The smallest side is the minimum of a
, b
, and c
; the largest side is the maximum of a
, b
, and c
; and the other side is the sum of a
, b
, and c
subtract the smallest side and the largest side. Then, all we need to do is check if the smallest side is larger than 0 and the square of the smallest side plus the square of the middle side is equal to the square of the largest side.
final int smallest = Math.min(a, Math.min(b, c));
final int largest = Math.max(a, Math.max(b, c));
final int middle = a + b + c - smallest - largest;
System.out.println(smallest > 0 && smallest * smallest + middle * middle == largest * largest);
Upvotes: 4