给定数学级数为3、9、21、41、71…对于给定的整数n,必须找到该级数的第n个数字。
例子 :
Input : n = 4
Output : 41
Input : n = 2
Output : 9
解决这个问题的首要任务是破解该系列。如果你介绍了一系列仔细一看,对于一般的n个项的值将是(σN2)+(σN)+1,其中
- (ΣN2):是第一n个自然数的平方和。
- (Σn) :是前n个自然数的总和。
- 1是一个简单的常数值。
因此,为了计算给定级数的第n个项,我们说f(n)有:
F(N)=(ΣN2)+(σN)+1
=((((n *(n + 1)*(2n + 1))/ 6)+(n *(n + 1)/ 2)+ 1
=(n 3 + 3n 2 + 2n + 3)/ 3
C++
// Program to calculate
// nth term of a series
#include
using namespace std;
// func for calualtion
int seriesFunc(int n)
{
// for summation of square
// of first n-natural nos.
int sumSquare = (n * (n + 1)
* (2 * n + 1)) / 6;
// summation of first n natural nos.
int sumNatural = (n * (n + 1) / 2);
// return result
return (sumSquare + sumNatural + 1);
}
// Driver Code
int main()
{
int n = 8;
cout << seriesFunc(n) << endl;
n = 13;
cout << seriesFunc(13);
return 0;
}
Java
// Java Program to calculate
// nth term of a series
import java.io.*;
class GFG
{
// func for calualtion
static int seriesFunc(int n)
{
// for summation of square
// of first n-natural nos.
int sumSquare = (n * (n + 1)
* (2 * n + 1)) / 6;
// summation of first n natural nos.
int sumNatural = (n * (n + 1) / 2);
// return result
return (sumSquare + sumNatural + 1);
}
// Driver Code
public static void main(String args[])
{
int n = 8;
System.out.println(seriesFunc(n));
n = 13;
System.out.println(seriesFunc(13));
}
}
// This code is contributed by Nikita Tiwari.
Python3
# Program to calculate
# nth term of a series
# func for calualtion
def seriesFunc(n):
# for summation of square
# of first n-natural nos.
sumSquare = (n * (n + 1) *
(2 * n + 1)) / 6
# summation of first n
# natural nos.
sumNatural = (n * (n + 1) / 2)
# return result
return (sumSquare + sumNatural + 1)
# Driver Code
n = 8
print (int(seriesFunc(n)))
n = 13
print (int(seriesFunc(n)))
# This is code is contributed by Shreyanshi Arun.
C#
// C# program to calculate
// nth term of a series
using System;
class GFG
{
// Function for calualtion
static int seriesFunc(int n)
{
// For summation of square
// of first n-natural nos.
int sumSquare = (n * (n + 1)
* (2 * n + 1)) / 6;
// summation of first n natural nos.
int sumNatural = (n * (n + 1) / 2);
// return result
return (sumSquare + sumNatural + 1);
}
// Driver Code
public static void Main()
{
int n = 8;
Console.WriteLine(seriesFunc(n));
n = 13;
Console.WriteLine(seriesFunc(13));
}
}
// This code is contributed by vt_m.
PHP
Javascript
输出 :
241
911