- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count number of right triangles possible with a given perimeter in C++
We are given a perimeter P of a triangle. Perimeter is the sum of all sides of the triangle. The goal is to find the number of right triangles that can be made which have the same perimeter.
If the sides of the triangle are a,b and c. Then a + b + c = P and a2 + b2 = c2 ( pythagoras theorem for any combination of a, b, and c )
We will check this by taking a from 1 to p/2 and b from a+1 to p/3. Then c = p-a-b (a+b+c=p)
For all right triangles, apply Pythagoras theorem. The values of a, b and c should also satisfy the condition of forming triangles where the sum of any two sides is always greater than third.
Let’s understand with examples.
Input − Perimeter P=12
Output − Total number of right triangles −1
Explanation −
The only values of a, b and c which satisfy a+b+c=P and a2 + b2 = c2 ( also sum of any two > third ) are 4, 3, and 5.
4+3+5=12, 3*3+4*4=5*5 ( 9+16=25 ) also 3+4>5, 4+5>3, 3+5>4
Input − Perimeter P=10
Output − Total number of right triangles −0
Explanation −
No values of a, b and c which could satisfy a+b+c=P and a2 + b2 = c2
Approach used in the below program is as follows
We take an integer variable perimeter which stores the value of the given perimeter.
Function rightTriangles(int p) takes the perimeter as input and returns the total number of right triangles that are possible.
Variable count stores the number of right triangles possible, initially 0.
Using for loop start for a=1 to p/2
Again using nested for loop start for b=a+1 to p/3 ( two sides are never equal in right triangles)
Calculate c=p-a-b. For this a,b,c check if (a+b>c && b+c>a && a+c>b).
Also check pythagoras theorem where a*a+b*b==c*c. If true increment count.
At the end return count contains the number of right triangles possible with a given perimeter.
Return count as desired result.
Note − we will check pythagoras theorem for only one combination of a,b and c for unique results.
Example
#include <bits/stdc++.h> using namespace std; int rightTriangles(int p){ int count = 0; int c=0; for( int a=1;a<p/2;a++){ for(int b=1;b<p/3;b++){ c=p-a-b; if( a+b>c && b+c>a && a+c>b) //condition for triangle{ if( (a*a+b*b)==c*c ) //pythagoras rule for right triangles { ++count; } } } } return count; } int main(){ int perimeter= 12; cout << "Total number of right triangles that can be formed: "<<rightTriangles(perimeter); return 0; }
Output
If we run the above code it will generate the following output −
Total number of right triangles that can be formed: 1