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 triangleint 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 Codeint 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 trianglestatic 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 codepublic 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 triangledef 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 Nn = 5Â
# Function callprint(right_angled(n))Â
# This code is contributed by code_hunt |
C#
// C# implementation of // the above approachusing System;Â
class GFG{     // Function to count total// number of right angled trianglestatic 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 Codepublic 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 trianglefunction 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 Nvar n = 5;Â
// Function calldocument.write(right_angled(n));Â
// This code is contributed by Amit Katiyar </script> |
1
Â
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 codepublic 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 approachimport 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 Nn=5Â
# Function Callprint(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 approachusing 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 |
1
Â
Time complexity: O(N2*log(N))Â as using sqrt inside inner for loopÂ
Auxiliary Space: O(N) since using auxiliary space for set
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Info to that Topic: geeksforgeeks.org/count-number-of-triangles-possible-with-length-of-sides-not-exceeding-n/ […]
… [Trackback]
[…] There you can find 25781 more Info on that Topic: geeksforgeeks.org/count-number-of-triangles-possible-with-length-of-sides-not-exceeding-n/ […]