Total number of triangles formed when there are H horizontal and V vertical lines
Last Updated :
07 Apr, 2021
Given a triangle ABC. H horizontal lines from side AB to AC (as shown in fig.) and V vertical lines from vertex A to side BC are drawn, the task is to find the total no. of triangles formed.
Examples:
Input: H = 2, V = 2
Output: 18
As we see in the image above, total triangles formed are 18.
Input: H = 3, V = 4
Output: 60
Approach: As we see in the images below, we can derive a general formula for above problem:
- If there are only h horizontal lines then total triangles are (h + 1).
- If there are only v vertical lines then total triangles are (v + 1) * (v + 2) / 2..
- So, total triangles are Triangles formed by horizontal lines * Triangles formed by vertical lines i.e. (h + 1) * (( v + 1) * (v + 2) / 2).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define LLI long long int
LLI totalTriangles(LLI h, LLI v)
{
if (h == 0 && v == 0)
return 1;
if (h == 0)
return ((v + 1) * (v + 2) / 2);
if (v == 0)
return (h + 1);
LLI Total = (h + 1) * ((v + 1) * (v + 2) / 2);
return Total;
}
int main()
{
int h = 2, v = 2;
cout << totalTriangles(h, v);
return 0;
}
|
Java
class GFG {
public static int totalTriangles( int h, int v)
{
if (h == 0 && v == 0 )
return 1 ;
if (h == 0 )
return ((v + 1 ) * (v + 2 ) / 2 );
if (v == 0 )
return (h + 1 );
int total = (h + 1 ) * ((v + 1 ) * (v + 2 ) / 2 );
return total;
}
public static void main(String[] args)
{
int h = 2 , v = 2 ;
System.out.print(totalTriangles(h, v));
}
}
|
C#
using System;
class GFG
{
public static int totalTriangles( int h, int v)
{
if (h == 0 && v == 0)
return 1;
if (h == 0)
return ((v + 1) * (v + 2) / 2);
if (v == 0)
return (h + 1);
int total = (h + 1) * ((v + 1) * (v + 2) / 2);
return total;
}
public static void Main()
{
int h = 2, v = 2;
Console.Write(totalTriangles(h, v));
}
}
|
Python3
def totalTriangles(h, v):
if (h = = 0 and v = = 0 ):
return 1
if (h = = 0 ):
return ((v + 1 ) * (v + 2 ) / 2 )
if (v = = 0 ):
return (h + 1 )
total = (h + 1 ) * ((v + 1 ) * (v + 2 ) / 2 )
return total
h = 2
v = 2
print ( int (totalTriangles(h, v)))
|
PHP
<?php
function totalTriangles( $h , $v )
{
if ( $h == 0 && $v == 0)
return 1;
if ( $h == 0)
return (( $v + 1) * ( $v + 2) / 2);
if ( $v == 0)
return ( $h + 1);
$Total = ( $h + 1) * (( $v + 1) *
( $v + 2) / 2);
return $Total ;
}
$h = 2;
$v = 2;
echo totalTriangles( $h , $v );
?>
|
Javascript
<script>
function totalTriangles(h , v)
{
if (h == 0 && v == 0)
return 1;
if (h == 0)
return ((v + 1) * (v + 2) / 2);
if (v == 0)
return (h + 1);
var total = (h + 1) * ((v + 1) * (v + 2) / 2);
return total;
}
var h = 2, v = 2;
document.write(totalTriangles(h, v));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...