Sponsored
Sponsored
To determine whether three segments can form a triangle, we can directly apply the triangle inequality theorem. For segments with lengths x
, y
, and z
to form a triangle, the following conditions must be met:
x + y > z
x + z > y
y + z > x
If all three conditions are satisfied, then the segments can form a triangle.
Time Complexity: O(1) per triangle check since we only run a constant number of comparisons.
Space Complexity: O(1) since no additional space proportional to input size is used.
1#include <iostream>
2using namespace std;
3
4void checkTriangle(int x, int y, int z) {
5 cout << x << " " << y << " " << z << " ";
6 if (x + y > z && x + z > y && y + z > x) {
7 cout << "Yes" << endl;
8 } else {
9 cout << "No" << endl;
10 }
11}
12
13int main() {
14 int triangles[][3] = {{13, 15, 30}, {10, 20, 15}};
15 int n = sizeof(triangles) / sizeof(triangles[0]);
16
17 for (int i = 0; i < n; i++) {
18 checkTriangle(triangles[i][0], triangles[i][1], triangles[i][2]);
19 }
20
21 return 0;
22}
In this C++ program, the function checkTriangle
evaluates whether given sides form a triangle. It uses cout
to output results for each of the sides stored in an array within the main function.
In this approach, we first sort the three sides so that we only need to check one inequality condition instead of three. Given sides x
, y
, and z
, sort them to be a ≤ b ≤ c
. Then check: a + b > c
.
Sorting reduces the number of comparisons and handles the integer sides efficiently when checking validity of the triangle.
Time Complexity: O(1) since sorting three items is constant time and checking has a constant cost.
Space Complexity: O(1).
class TriangleCheck {
static void CheckTriangle(int x, int y, int z) {
int[] sides = new int[] {x, y, z};
Array.Sort(sides);
string result = (sides[0] + sides[1] > sides[2]) ? "Yes" : "No";
Console.WriteLine($"{x} {y} {z} {result}");
}
static void Main() {
int[][] triangles = new int[][] {new int[] {13, 15, 30}, new int[] {10, 20, 15}};
foreach (var sides in triangles) {
CheckTriangle(sides[0], sides[1], sides[2]);
}
}
}
This C# implementation sorts an array of triangle side lengths using Array.Sort
, optimizing the checks to just one inequality for determining triangle validity.