给定数字N ,任务是找到前N个Pronic数的总和。
The numbers that can be arranged to form a rectangle are called Rectangular Numbers (also known as Pronic numbers). The first few rectangular numbers are:
0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462 . . . .
例子:
Input: N = 4
Output: 20
Explanation:
0, 2, 6, 12 are the first 4 pronic numbers.
Input: N = 3
Output: 8
方法:
- 令,第N项由T N表示。可以通过如下拆分每个术语来轻松解决此问题:
所以:
SN = Sum of N Pronic Numbers
下面是上述方法的实现:
C++
// C++ implementation to find
// sum of first N terms
#include
using namespace std;
// Function to calculate the sum
int calculateSum(int N)
{
return N * (N - 1) / 2
+ N * (N - 1)
* (2 * N - 1) / 6;
}
// Driver code
int main()
{
int N = 3;
cout << calculateSum(N);
return 0;
}
Java
// Java implementation implementation to find
// sum of first N terms
class GFG{
// Function to calculate the sum
static int calculateSum(int N)
{
return N * (N - 1) / 2 + N * (N - 1) *
(2 * N - 1) / 6;
}
// Driver code
public static void main (String[] args)
{
int N = 3;
System.out.println(calculateSum(N));
}
}
// This code is contributed by Pratima Pandey
Python3
# Python3 implementation to find
# sum of first N terms
# Function to calculate the sum
def calculateSum(N):
return (N * (N - 1) // 2 +
N * (N - 1) * (2 *
N - 1) // 6);
# Driver code
N = 3;
print(calculateSum(N));
# This code is contributed by Code_Mech
C#
// C# implementation implementation to find
// sum of first N terms
using System;
class GFG{
// Function to calculate the sum
static int calculateSum(int N)
{
return N * (N - 1) / 2 + N * (N - 1) *
(2 * N - 1) / 6;
}
// Driver code
public static void Main()
{
int N = 3;
Console.Write(calculateSum(N));
}
}
// This code is contributed by Code_Mech
输出:
8
时间复杂度: O(1)。