Count of ways to split N into Triplets forming a Triangle
Last Updated :
11 Jun, 2021
Given an integer N, the task is to find the number of ways to split N into ordered triplets which can together form a triangle.
Examples:
Input: N = 15
Output: Total number of triangles possible are 28
Input: N = 9
Output: Total number of triangles possible is 10
Approach: The following observation needs to be made in order to solve the problem:
If N is split into 3 integers a, b and c, then the following conditions need to be satisfied for a, b and c to form a triangle:
- a + b > c
- a + c > b
- b + c > a
Therefore, iterate over the range [1, N] using nested loops to generate triplets, and for each triplet check if it forms a triangle or not.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int Numberofways( int n)
{
int count = 0;
for ( int a = 1; a < n; a++) {
for ( int b = 1; b < n; b++) {
int c = n - (a + b);
if (a + b > c && a + c > b
&& b + c > a) {
count++;
}
}
}
return count;
}
int main()
{
int n = 15;
cout << Numberofways(n) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static int Numberofways( int n)
{
int count = 0 ;
for ( int a = 1 ; a < n; a++) {
for ( int b = 0 ; b < n; b++) {
int c = n - (a + b);
if (a + b > c && a + c > b
&& b + c > a) {
count++;
}
}
}
return count;
}
public static void main(String[] args)
{
int n = 15 ;
System.out.println(Numberofways(n));
}
}
|
Python3
def Numberofways(n):
count = 0
for a in range ( 1 , n):
for b in range ( 1 , n):
c = n - (a + b)
if (a < b + c and b < a + c and c < a + b):
count + = 1
return count
n = 15
print (Numberofways(n))
|
C#
using System;
class GFG {
static int Numberofways( int n)
{
int count = 0;
for ( int a = 1; a < n; a++) {
for ( int b = 1; b < n; b++) {
int c = n - (a + b);
if (a + b > c && a + c > b
&& b + c > a) {
count++;
}
}
}
return count;
}
static public void Main()
{
int n = 15;
Console.WriteLine(Numberofways(n));
}
}
|
Javascript
<script>
function Numberofways(n)
{
var count = 0;
for ( var a = 1; a < n; a++)
{
for ( var b = 1; b < n; b++)
{
var c = n - (a + b);
if (a + b > c && a + c > b
&& b + c > a)
{
count++;
}
}
}
return count;
}
var n = 15;
document.write( Numberofways(n));
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...