Given a positive integer S, the task is to find the length of diagonal of a square having sides of length S.
Input: S = 10
Explanation: The length of the diagonal of a square whose sides are of length 10 is 14.1421
Input: S = 24
Approach: The given problem can be solved based on the mathematical relation between the length of sides of a square and the length of diagonal of a square as illustrated below:
As visible from the above image, the diagonal and the two sides of the square form a right-angled triangle. Therefore, by applying Pythagoras Theorem:
(hypotenuse)2 = (base)2 + (perpendicular)2, where D and S are length of the diagonal and the square.
Therefore, simply calculate the length of the diagonal using the above-derived relation.
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.