Sum of all the numbers present at given level in Pascal’s triangle
Last Updated :
15 Dec, 2022
Given a level L. The task is to find the sum of all the integers present at the given level in Pascal’s triangle .
A Pascal triangle with 6 levels is shown below:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Examples:
Input: L = 3
Output: 4
1 + 2 + 1 = 4
Input: L = 2
Output:2
Approach: If we observe carefully the series of the sum of levels will go on like 1, 2, 4, 8, 16…., which is a GP series with a = 1 and r = 2.
Therefore, sum of Lth level is L’th term in the above series.
Lth term = 2L-1
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int sum( int h)
{
return pow (2, h - 1);
}
int main()
{
int L = 3;
cout << sum(L);
return 0;
}
|
Java
class GFG
{
static int sum( int h)
{
return ( int )Math.pow( 2 , h - 1 );
}
public static void main (String[] args)
{
int L = 3 ;
System.out.println(sum(L));
}
}
|
Python3
def summ(h):
return pow ( 2 , h - 1 )
L = 3
print (summ(L))
|
C#
using System;
class GFG
{
static int sum( int h)
{
return ( int )Math.Pow(2, h - 1);
}
public static void Main ()
{
int L = 3;
Console.WriteLine(sum(L));
}
}
|
Javascript
<script>
function sum(h)
{
return Math.pow(2, h - 1);
}
var L = 3;
document.write(sum(L));
</script>
|
Time Complexity: O(log2L) because it is using pow function
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...