给定正整数N ,任务是找到下三角形的第N行中所有数字的总和。
1
3 2
6 2 3
10 2 3 4
15 2 3 4 5
…
…
…
例子:
Input: N = 2
Output: 5
3 + 2 = 5
Input: N = 3
Output: 11
6 + 2 + 3 = 11
方法:仔细观察图案,可以看到将形成一个序列,分别为1、5、11、19、29、41、55,…… ,第N个项是(N – 1)+ N 2 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
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
输出:
11