给定一个整数N和一个序列(1),(3、5),(7、9、11),(13、15、17、19),…..任务是找到其中所有数字的总和。第N个括号。
例子:
Input: N = 2
Output: 8
3 + 5 = 8
Input: N = 3
Output: 27
7 + 9 + 11 = 27
方法:可以观察到,对于N = 1,2,3,…的序列将形成为1,8,27,64,125,216,343,…,其第N个项是N 3
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the sum of the
// numbers in the nth parenthesis
int findSum(int n)
{
return pow(n, 3);
}
// Driver code
int main()
{
int n = 3;
cout << findSum(n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the sum of the
// numbers in the nth parenthesis
static int findSum(int n)
{
return (int)Math.pow(n, 3);
}
// Driver code
public static void main(String[] args)
{
int n = 3;
System.out.println(findSum(n));
}
}
// This code is contributed by Code_Mech
Python3
# Python3 implementation of the approach
# Function to return the sum of the
# numbers in the nth parenthesis
def findSum(n) :
return n ** 3;
# Driver code
if __name__ == "__main__" :
n = 3;
print(findSum(n));
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the sum of the
// numbers in the nth parenthesis
static int findSum(int n)
{
return (int)Math.Pow(n, 3);
}
// Driver code
public static void Main(String[] args)
{
int n = 3;
Console.WriteLine(findSum(n));
}
}
// This code is contributed by 29AjayKumar
Javascript
输出:
27
时间复杂度: O(1)