Sum of all the numbers in the Nth row of the given triangle
Given a positive integer N, the task is to find the sum of all the numbers in the Nth row of the below triangle.
1
3 2
6 2 3
10 2 3 4
15 2 3 4 5
…
…
…
Examples:
Input: N = 2
Output: 5
3 + 2 = 5
Input: N = 3
Output: 11
6 + 2 + 3 = 11
Approach: Taking a closer look at the pattern, it can be observed that a series will be formed as 1, 5, 11, 19, 29, 41, 55, … whose Nth term is (N – 1) + N2.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the sum // of the nth row elements of // the given triangle int getSum( int n) { return ((n - 1) + pow (n, 2)); } // Driver code int main() { int n = 3; cout << getSum(n); return 0; } |
Java
// Java implementation of the approach class GFG { // Function to return the sum // of the nth row elements of // the given triangle static int getSum( int n) { return ((n - 1 ) + ( int )Math.pow(n, 2 )); } // Driver code public static void main(String[] args) { int n = 3 ; System.out.println(getSum(n)); } } // This code is contributed by Code_Mech |
Python3
# Python3 implementation of the approach # Function to return the sum # of the nth row elements of # the given triangle def getSum(n) : return ((n - 1 ) + pow (n, 2 )); # Driver code if __name__ = = "__main__" : n = 3 ; print (getSum(n)); # This code is contributed by AnkitRai01 |
C#
// C# implementation of the approach using System; class GFG { // Function to return the sum // of the nth row elements of // the given triangle static int getSum( int n) { return ((n - 1) + ( int )Math.Pow(n, 2)); } // Driver code public static void Main(String[] args) { int n = 3; Console.WriteLine(getSum(n)); } } // This code is contributed by 29AjayKumar |
Javascript
<script> // Javascript implementation of the approach // Function to return the sum // of the nth row elements of // the given triangle function getSum(n) { return ((n - 1) + Math.pow(n, 2)); } // Driver code var n = 3; document.write(getSum(n)); </script> |
Output:
11