Professional Documents
Culture Documents
Y11 Project
Y11 Project
View Discussion
Improve Article
Save Article
Last Updated :
07 Apr, 2021
Read
Discuss
View Discussion
Improve Article
Save Article
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:
1/12
Input: H = 2, V = 2
Output: 18
Input: H = 3, V = 4
Output: 60
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Approach: As we see in the images below, we can derive a general formula for above
problem:
1. If there are only h horizontal lines then total triangles are (h + 1).
2. If there are only v vertical lines then total triangles are (v + 1) * (v + 2) / 2..
1. So, total triangles are Triangles formed by horizontal lines * Triangles formed
by vertical lines i.e. (h + 1) * (( v + 1) * (v + 2) / 2).
2/12
Below is the implementation of the above approach:
C++
3/12
// C++ implementation of the approach
#include <bits/stdc++.h>
if (h == 0 && v == 0)
return 1;
if (h == 0)
if (v == 0)
return (h + 1);
return Total;
// Driver code
int main()
int h = 2, v = 2;
return 0;
4/12
Java
5/12
// Java implementation of the approach
class GFG {
if (h == 0 && v == 0 )
return 1 ;
if (h == 0 )
return ((v + 1 ) * (v + 2 ) / 2 );
if (v == 0 )
return (h + 1 );
return total;
// Driver code
int h = 2 , v = 2 ;
System.out.print(totalTriangles(h, v));
C#
6/12
7/12
// C# implementation of the approach
using System;
class GFG
if (h == 0 && v == 0)
return 1;
if (h == 0)
if (v == 0)
return (h + 1);
return total;
// Driver code
int h = 2, v = 2;
Console.Write(totalTriangles(h, v));
8/12
Python3
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
# Driver code
h = 2
v = 2
PHP
9/12
<?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 ;
// Driver code
$h = 2;
$v = 2;
echo totalTriangles( $h , $v );
?>
10/12
Javascript
<script>
function totalTriangles(h , v)
if (h == 0 && v == 0)
return 1;
if (h == 0)
if (v == 0)
return (h + 1);
return total;
// Driver code
var h = 2, v = 2;
document.write(totalTriangles(h, v));
</script>
11/12
Output:
18
My Personal Notes
arrow_drop_up
Article Contributed By :
Chandan_Agrawal
@Chandan_Agrawal
Vote for difficulty
Report Issue
12/12