Find other two sides of a right angle triangle in C++


In this problem, we are given an integer a denoting one side of a right angle triangle. We need to check whether it is possible to have a right angle triangle with side a. If it is possible, then find the other two sides of a right angle triangle.

Let’s take an example to understand the problem,

Input

a = 5

Output

Sides : 5, 12, 13

Explanation

The sides of right angle are found as 52 + 122 = 132

Solution Approach

A simple solution to the problem is using pythagoras theorem. We know that the sides of a right angled triangle follow pythagoras theorem, which is

a2 + b2 = c2

Where a and b are sides of the triangle and c is the hypotenuse of the triangle.

Using this, we will calculate values of b and c using a.

Case 1

If a is even,
c = (a2 + 4) + 1
b = (a2 + 4) - 1

Case 2

If a is odd,
c = (a2 + 1)/ 2
c = (a2 - 1)/ 2

Program to illustrate the working of our solution,

Example

 Live Demo

#include <bits/stdc++.h>
#include <cmath>
using namespace std;
#define PI 3.1415926535
void printOtherSides(int n) {
   int b,c;
   if (n & 1) {
      if (n == 1)
         cout << -1 << endl;
      else{
         b = (n*n-1)/2;
         c = (n*n+1)/2;
      }
   } else {
      if (n == 2)
         cout << -1 << endl;
      else{
         b = n*n/4-1;
         c = n*n/4+1;
      }
   }
   cout<<"Sides : a = "<<n<<", b = "<<b<<", c = "<<c<<endl;
}
int main() {
   int a = 5;
   printOtherSides(a);
   return 0;
}

Output

Sides : a = 5, b = 12, c = 13

Updated on: 16-Mar-2021

188 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements