Count number of triangles possible with length of sides not exceeding N
Last Updated :
15 Jul, 2025
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
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem