📌  相关文章
📜  给定三角形的第N行中所有数字的总和

📅  最后修改于: 2021-04-22 03:32:17             🧑  作者: Mango

给定正整数N ,任务是找到下三角形的N行中所有数字的总和。

例子:

方法:仔细观察图案,可以看到将形成一个序列,分别为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