求系列 12, 14, 24, 58, 164, ... 的 N 项之和
给定一个正整数N 。求系列12, 14, 24, 58, 164, ....的前N 项之和
例子:
Input: N = 5
Output: 272
Input: N = 3
Output: 50
方法:
该序列是通过使用以下模式形成的。对于任何值 N-
SN = 3N – N2 + 11 * N – 1
插图:
Input: N = 5
Output: 272
Explanation:
SN = 3N – N2 + 11 * N – 1
= 35 – 52 + 11 * 5 – 1
= 243 – 25 + 54
= 272
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Function to return sum of
// N term of the series
int findSum(int N)
{
return (pow(3, N) -
pow(N, 2) +
11 * N - 1);
}
// Driver Code
int main()
{
int N = 5;
cout << findSum(N);
return 0;
}
Java
// Java program to implement
// the above approach
class GFG {
// Function to return sum of
// N term of the series
static int findSum(int N) {
return (int) (Math.pow(3, N) - Math.pow(N, 2) + 11 * N - 1);
}
// Driver Code
public static void main(String args[]) {
int N = 5;
System.out.print(findSum(N));
}
}
// This code is contributed by saurabh_jaiswal.
Python3
# Python code for the above approach
# Function to return sum of
# N term of the series
def findSum(N):
return ((3 ** N) -
(N ** 2) +
11 * N - 1);
# Driver Code
# Get the value of N
N = 5;
print(findSum(N));
# This code is contributed by Saurabh Jaiswal
C#
// C# program to implement
// the above approach
using System;
class GFG
{
// Function to return sum of
// N term of the series
static int findSum(int N) {
return (int) (Math.Pow(3, N) - Math.Pow(N, 2) + 11 * N - 1);
}
// Driver Code
public static void Main()
{
int N = 5;
Console.Write(findSum(N));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
272
时间复杂度: O(1)
辅助空间: O(1)