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.
1using System;
2
3class TriangleCheck {
4 static void CheckTriangle(int x, int y, int z) {
5 string result = (x + y > z && x + z > y && y + z > x) ? "Yes" : "No";
6 Console.WriteLine($"{x} {y} {z} {result}");
7 }
8
9 static void Main() {
10 int[][] triangles = new int[][] {new int[] {13, 15, 30}, new int[] {10, 20, 15}};
11 foreach (var sides in triangles) {
12 CheckTriangle(sides[0], sides[1], sides[2]);
13 }
14 }
15}
This C# program defines a static method CheckTriangle
that uses a conditional check to determine if three sides can form a triangle and outputs the result.
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).
#include <algorithm>
using namespace std;
void checkTriangle(int x, int y, int z) {
int sides[] = {x, y, z};
sort(sides, sides + 3);
cout << x << " " << y << " " << z << " ";
if (sides[0] + sides[1] > sides[2]) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
int main() {
int triangles[][3] = {{13, 15, 30}, {10, 20, 15}};
int n = sizeof(triangles) / sizeof(triangles[0]);
for (int i = 0; i < n; i++) {
checkTriangle(triangles[i][0], triangles[i][1], triangles[i][2]);
}
return 0;
}
This C++ program employs the sort
function from the algorithm
library to sort the side lengths and then checks the primary inequality for a triangle.