Count number of triangles possible with length of sides not exceeding N
Last Updated :
23 Feb, 2023
Given an integer N, the task is to find the total number of right angled triangles that can be formed such that the length of any side of the triangle is at most N.
A right-angled triangle satisfies the following condition: X2 + Y2 = Z2 where Z represents the length of the hypotenuse, and X and Y represent the lengths of the remaining two sides.
Examples:
Input: N = 5
Output: 1
Explanation:
The only possible combination of sides which form a right-angled triangle is {3, 4, 5}.
Input: N = 10
Output: 2
Explanation:
Possible combinations of sides which form a right-angled triangle are {3, 4, 5} and {6, 8, 10}.
Naive Approach: The idea is to generate every possible combination of triplets with integers from the range [1, N] and for each such combination, check whether it is a right-angled triangle or not.
Below is the implementation of the above approach:
C++
// C++ implementation of
// the above approach
#include<bits/stdc++.h>
using namespace std;
// Function to count total
// number of right angled triangle
int right_angled(int n)
{
// Initialise count with 0
int count = 0;
// Run three nested loops and
// check all combinations of sides
for (int z = 1; z <= n; z++) {
for (int y = 1; y <= z; y++) {
for (int x = 1; x <= y; x++) {
// Condition for right
// angled triangle
if ((x * x) + (y * y) == (z * z)) {
// Increment count
count++;
}
}
}
}
return count;
}
// Driver Code
int main()
{
// Given N
int n = 5;
// Function Call
cout << right_angled(n);
return 0;
}
Java
// Java implementation of
// the above approach
import java.io.*;
class GFG{
// Function to count total
// number of right angled triangle
static int right_angled(int n)
{
// Initialise count with 0
int count = 0;
// Run three nested loops and
// check all combinations of sides
for(int z = 1; z <= n; z++)
{
for(int y = 1; y <= z; y++)
{
for(int x = 1; x <= y; x++)
{
// Condition for right
// angled triangle
if ((x * x) + (y * y) == (z * z))
{
// Increment count
count++;
}
}
}
}
return count;
}
// Driver code
public static void main (String[] args)
{
// Given N
int n = 5;
// Function call
System.out.println(right_angled(n));
}
}
// This code is contributed by code_hunt
Python3
# Python implementation of
# the above approach
# Function to count total
# number of right angled triangle
def right_angled(n):
# Initialise count with 0
count = 0
# Run three nested loops and
# check all combinations of sides
for z in range(1, n + 1):
for y in range(1, z + 1):
for x in range(1, y + 1):
# Condition for right
# angled triangle
if ((x * x) + (y * y) == (z * z)):
# Increment count
count += 1
return count
# Driver Code
# Given N
n = 5
# Function call
print(right_angled(n))
# This code is contributed by code_hunt
C#
// C# implementation of
// the above approach
using System;
class GFG{
// Function to count total
// number of right angled triangle
static int right_angled(int n)
{
// Initialise count with 0
int count = 0;
// Run three nested loops and
// check all combinations of sides
for(int z = 1; z <= n; z++)
{
for(int y = 1; y <= z; y++)
{
for(int x = 1; x <= y; x++)
{
// Condition for right
// angled triangle
if ((x * x) + (y * y) == (z * z))
{
// Increment count
count++;
}
}
}
}
return count;
}
// Driver Code
public static void Main(string[] args)
{
// Given N
int n = 5;
// Function call
Console.Write(right_angled(n));
}
}
// This code is contributed by rutvik_56
JavaScript
<script>
// javascript implementation of
// the above approach
// Function to count total
// number of right angled triangle
function right_angled(n)
{
// Initialise count with 0
var count = 0;
// Run three nested loops and
// check all combinations of sides
for(z = 1; z <= n; z++)
{
for(y = 1; y <= z; y++)
{
for(x = 1; x <= y; x++)
{
// Condition for right
// angled triangle
if ((x * x) + (y * y) == (z * z))
{
// Increment count
count++;
}
}
}
}
return count;
}
// Driver code
//Given N
var n = 5;
// Function call
document.write(right_angled(n));
// This code is contributed by Amit Katiyar
</script>
Time complexity: O(N3)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the idea that the third side of the triangle can be found out, if the two sides of the triangles are known. Follow the steps below to solve the problem:
- Iterate up to N and generate pairs of possible length of two sides and find the third side using the relation x2 + y2 = z2
- If sqrt(x2+y2) is found to be an integer, store the three concerned integers in a Set in sorted order, as they can form a right angled triangle.
- Print the final size of the set as the required count.
Below is the implementation of the above approach:
C++
// C++ implementation of the
// above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count total
// number of right angled triangle
int right_angled(int n)
{
// Consider a set to store
// the three sides
set<pair<int, pair<int, int> > > s;
// Find possible third side
for (int x = 1; x <= n; x++) {
for (int y = 1; y <= n; y++) {
// Condition for a right
// angled triangle
if (x * x + y * y <= n * n) {
int z = sqrt(x * x + y * y);
// Check if the third side
// is an integer
if (z * z != (x * x + y * y))
continue;
vector<int> v;
// Push the three sides
v.push_back(x);
v.push_back(y);
v.push_back(sqrt(x * x + y * y));
sort(v.begin(), v.end());
// Insert the three sides in
// the set to find unique triangles
s.insert({ v[0], { v[1], v[2] } });
}
else
break;
}
}
// return the size of set
return s.size();
}
// Driver code
int main()
{
// Given N
int n = 5;
// Function Call
cout << right_angled(n);
return 0;
}
Java
// Java implementation of the
// above approach
import java.util.*;
class Pair<F, S>
{
// First member of pair
private F first;
// Second member of pair
private S second;
public Pair(F first, S second)
{
this.first = first;
this.second = second;
}
}
class GFG{
// Function to count total
// number of right angled triangle
public static int right_angled(int n)
{
// Consider a set to store
// the three sides
Set<Pair<Integer,
Pair<Integer,
Integer>>> s = new HashSet<Pair<Integer,
Pair<Integer,
Integer>>>();
// Find possible third side
for(int x = 1; x <= n; x++)
{
for(int y = 1; y <= n; y++)
{
// Condition for a right
// angled triangle
if (x * x + y * y <= n * n)
{
int z = (int)Math.sqrt(x * x + y * y);
// Check if the third side
// is an integer
if (z * z != (x * x + y * y))
continue;
Vector<Integer> v = new Vector<Integer>();
// Push the three sides
v.add(x);
v.add(y);
v.add((int)Math.sqrt(x * x + y * y));
Collections.sort(v);
// Add the three sides in
// the set to find unique triangles
s.add(new Pair<Integer,
Pair<Integer,
Integer>>(v.get(0),
new Pair<Integer,
Integer>(v.get(1),
v.get(2))));
}
else
break;
}
}
// Return the size of set
return s.size() - 1;
}
// Driver code
public static void main(String[] args)
{
// Given N
int n = 5;
// Function call
System.out.println(right_angled(n));
}
}
// This code is contributed by grand_master
Python3
# Python implementation of the
# above approach
import math
# Function to count total
# number of right angled triangle
def right_angled(n):
# Consider a set to store
# the three sides
s={}
# Find possible third side
for x in range(1,n+1):
for y in range(1,n+1):
# Condition for a right
# angled triangle
if(x*x+y*y<=n*n):
z=int(math.sqrt(x*x+y*y))
# Check if the third side
# is an integer
if (z*z!=(x*x+y*y)):
continue
v=[]
# Push the three sides
v.append(x)
v.append(y)
v.append(int(math.sqrt(x*x+y*y)))
v.sort()
# Insert the three sides in
# the set to find unique triangles
s[v[0]]=[v[1],v[2]]
else:
break
# return the size of set
return len(s)
# Driver code
# Given N
n=5
# Function Call
print(right_angled(n))
# This code is contributed by Aman Kumar.
JavaScript
// JavaScript implementation of the
// above approach
// Function to count total
// number of right angled triangle
function right_angled(n)
{
// Consider a set to store
// the three sides
let s = new Set();
// Find possible third side
for (let x = 1; x <= n; x++) {
for (let y = 1; y <= n; y++) {
// Condition for a right
// angled triangle
if (x * x + y * y <= n * n) {
let z = Math.floor(Math.sqrt(x * x + y * y));
// Check if the third side
// is an integer
if (z * z != (x * x + y * y))
continue;
let v = new Array();
// Push the three sides
v.push(x);
v.push(y);
v.push(Math.floor(Math.sqrt(x * x + y * y)));
v.sort();
// Insert the three sides in
// the set to find unique triangles
s.add([v[0],[v[1], v[2]]].join());
}
else
break;
}
}
// return the size of set
return s.size;
}
// Driver code
// Given N
let n = 5;
// Function Call
console.log(right_angled(n));
// The code is contributed by Gautam goel (gautamgoel962)
C#
// C# implementation of the
// above approach
using System;
using System.Collections.Generic;
class Pair<F, S> {
// First member of pair
private F first;
// Second member of pair
private S second;
public Pair(F first, S second)
{
this.first = first;
this.second = second;
}
}
class GFG {
// Function to count total
// number of right angled triangle
public static int right_angled(int n)
{
// Consider a set to store
// the three sides
HashSet<Pair<int, Pair<int, int> > > s
= new HashSet<Pair<int, Pair<int, int> > >();
// Find possible third side
for (int x = 1; x <= n; x++) {
for (int y = 1; y <= n; y++) {
// Condition for a right
// angled triangle
if (x * x + y * y <= n * n) {
int z = (int)Math.Sqrt(x * x + y * y);
// Check if the third side
// is an integer
if (z * z != (x * x + y * y))
continue;
List<int> v = new List<int>();
// Push the three sides
v.Add(x);
v.Add(y);
v.Add((int)Math.Sqrt(x * x + y * y));
v.Sort();
// Add the three sides in
// the set to find unique triangles
s.Add(new Pair<int, Pair<int, int> >(
v[0],
new Pair<int, int>(v[1], v[2])));
}
else
break;
}
}
// Return the size of set
return s.Count - 1;
}
// Driver code
public static void Main(string[] args)
{
// Given N
int n = 5;
// Function call
Console.WriteLine(right_angled(n));
}
}
// This code is contributed by phasing17
Time complexity: O(N2*log(N)) as using sqrt inside inner for loop
Auxiliary Space: O(N) since using auxiliary space for set
Similar Reads
Count number of triplets with product not exceeding a given number Given a positive integer N, the task is to find the number of triplets of positive integers (X, Y, Z), whose product is at most N. Examples: Input: N = 2Output: 4Explanation: Below are the triplets whose product is at most N(= 2): (1, 1, 1): Product is 1*1*1 = 1.(1, 1, 2): Product is 1*1*2 = 2.(1, 2
5 min read
Number of triangles possible with given lengths of sticks which are powers of 2 Given an array of N integers where arr[i] denotes the number of sticks of length 2i. The task is to find the number of triangles possible with given lengths having area ? 0. Note: Every stick can only be used once. Examples: Input: a[] = {1, 2, 2, 2, 2} Output: 3 All possible triangles are: (20, 24,
7 min read
Count number of right triangles possible with a given perimeter Given a perimeter P, the task is to find the number of right triangles possible with perimeter equal to p.Examples: Input: P = 12 Output: number of right triangles = 1 The only right angle possible is with sides hypotenuse = 5, perpendicular = 4 and base = 3. Input: p = 840 Output: number of right t
6 min read
Count number of triangles possible for the given sides range Given four integers A, B, C, and D, the task is to find the number of distinct sets (X, Y, and Z) where X, Y and Z denotes the length of sides forming a valid triangle. A ? X ? B, B ? Y ? C, and C ? Z ? D.Examples: Input: A = 2, B = 3, C = 4, D = 5 Output: 7 Explanation: Possible Length of Side of T
10 min read
Number of triangles formed by joining vertices of n-sided polygon with two common sides and no common sides Given N-sided polygon we need to find the total number of triangles formed by joining the vertices of the given polygon with exactly two sides being common and no side being common.Examples: Input : N = 6 Output : 6 2 The image below is of a triangle forming inside a Hexagon by joining vertices as s
5 min read