Given a level N, the task is to find the sum of all the integers present at this given level in an Alternating Pascal’s triangle.
A Modified Pascal triangle with 5 levels is shown below.
1 -1 1 1 -2 1 -1 3 -3 1 1 -4 6 -4 1
Examples:
Input: N = 1 Output: 1 Input: N = 2 Output: 0
Approach: As we can observe for even level sum is 0 and for odd level except for 1 sum is also 0. So There can be at most 2 cases:
- If L = 1, then the answer is 1.
- Otherwise, the answer will always be 0.
Below is the implementation of the above approach:
C++
// C++ program to calculate sum of // all the numbers present at given // level in an Modified Pascal’s triangle #include <bits/stdc++.h> using namespace std;
// Function to calculate sum void ans( int n)
{ if (n == 1)
cout << "1" ;
else
cout << "0" ;
} // Driver Code int main()
{ int n = 2;
ans(n);
return 0;
} |
Java
// Java program to calculate sum of // all the numbers present at given // level in an Modified Pascal's triangle import java.io.*;
public class GFG {
// Function to calculate sum
static void ans( int n)
{
if (n == 1 )
System.out.println( "1" );
else
System.out.println( "0" );
}
// Driver Code
public static void main(String[] args)
{
int n = 2 ;
ans(n);
}
} // This code is contributed by 29AjayKumar |
Python3
# Python3 program to calculate sum of # all the numbers present at given # level in an Modified Pascal’s triangle # Function to calculate sum def ans(n) :
if (n = = 1 ) :
print ( "1" ,end = "");
else :
print ( "0" ,end = "");
# Driver Code if __name__ = = "__main__" :
n = 2 ;
ans(n);
# This code is contributed by AnkitRai01 |
C#
// C# program to calculate sum of // all the numbers present at given // level in an Modified Pascal's triangle using System;
class GFG
{ // Function to calculate sum static void ans( int n)
{ if (n == 1)
Console.WriteLine( "1" );
else
Console.WriteLine( "0" );
} // Driver Code public static void Main(String[] args)
{ int n = 2;
ans(n);
} } // This code is contributed by 29AjayKumar |
Javascript
<script> // Javascript program to calculate sum of // all the numbers present at given // level in an Modified Pascal’s triangle // Function to calculate sum function ans(n)
{ if (n == 1)
document.write( "1" );
else
document.write( "0" );
} // Driver Code var n = 2;
ans(n); // This code is contributed by rutvik_56 </script> |
Output:
0
Time Complexity: O(1)
Auxiliary Space: O(1)
Recommended Articles