Loading...
The Triangle Inequality Theorem states that it is possible to construct a triangle only when the sum of any two sides of it is greater than the third side. To furthur simply the statement, let's assume the three numbers representing the lengths of the sides of a triangle to be a
, b
, and c
. A triangle can be formed if and only if the following conditions hold:
a + b > c
a + c > b
b + c > a
If any of these conditions is not met, it is impossible to create a valid triangle with those side lengths.
The problem requires the creation of a smart contract with a public function check()
. This function takes three unsigned integer parameters: a
, b
, and c
, representing the lengths of the sides of the triangle. It should return a boolean value, true
if a triangle can be formed with these side lengths and false
if it's not possible to form a triangle.
function check(uint a, uint b, uint c) public pure returns (bool)
You are expected to implement the logic inside this function to check if the given side lengths adhere to the Triangle Inequality Theorem and return the appropriate boolean value.
As we discussed, we just need to check the 3 conditions and if any one of them fails to satisfy then the function should return false. Let us implement this logic in solidity.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract TriangleInequality {
//To check if a triangle is possible with lengths a,b and c
function check(uint a, uint b, uint c) public pure returns (bool) {
return a + b > c && a + c > b && b + c > a;
}
}
In this solidity code we are declaring a smart contract named TriangleInequality
. Inside of that contract we are defining a public function check
which takes three uint
(Unsigned integers) a
, b
, and c
and it returns a boolean value (true
or false
). Inside the function we have a single statement, This checks all the three conditions which are discussed above. We are using 'logical and' operator (&&
) which returns true
when both the conditions with it are true
. If any of the condition is false, the operator will altogether return false
. This code accomplishes our goal in a very simple way.
Hopefully you understood how to go about a problem and think of how to the logic. Then we went furthur to implement the logic in our code. Good luck for future problems. Keep practising!