Write a program to check whether the given three sides can form a triangle or not.
For three sides a, b, and c to form a valid triangle, they must satisfy:
a + b > c
a + c > b
b + c > a
All three conditions must be true simultaneously.
A valid triangle: a + b > c, a + c > b, b + c > a
Accept three integer as a input
Print the output as "Valid" or "Not Valid"
1 <= INPUT <= 10^15
#include <iostream> using namespace std; int main() { long long a, b, c; cin >> a >> b >> c; // Check for triangle validity using the triangle inequality theorem if ((a + b > c) && (a + c > b) && (b + c > a)) cout << "Valid"; else cout << "Not Valid"; return 0; }
>
instead of >=
is crucialImagine trying to build a triangle with sticks:
Key Insight: The sum of two smaller sides must be strictly greater than the largest side to "close" the triangle.
int
instead of long long
for large valuesYou can optimize by finding the maximum side first:
// Find the maximum side long long max_side = max({a, b, c}); long long sum_other_two = a + b + c - max_side; // Only need to check if sum of two smaller > largest if (sum_other_two > max_side) cout << "Valid"; else cout << "Not Valid";
Why this works: If the two smaller sides sum to more than the largest, all three triangle inequality conditions are automatically satisfied.
Once you know it's a valid triangle, you can classify it: