给定一个系列9,33,73,129…找到该系列的第n个项。
例子:
Input : n = 4
Output : 129
Input : n = 5
Output : 201
给定的序列具有一个模式,该模式在移动一格后从其自身中减去就可以看到
S = 9 + 33 + 73 + 129 + … tn-1 + tn
S = 9 + 33 + 73 + … tn-2 + tn-1 + tn
———————————————
0 = 9 + (24 + 40 + 56 + ….) - tn
Since 24 + 40 + 56.. series in A.P with
common difference of 16, we get
tn = 9 + [((n-1)/2)*(2*24 + (n-1-1)d)]
On solving this we get
tn = 8n2 + 1
下面是上述方法的实现:
C++
// Program to find n-th element in the
// series 9, 33, 73, 128..
#include
using namespace std;
// Returns n-th element of the series
int series(int n)
{
return (8 * n * n) + 1;
}
// driver program to test the above function
int main()
{
int n = 5;
cout << series(n);
return 0;
}
Java
// Program to find n-th element in the
// series 9, 33, 73, 128..
import java.io.*;
class GFG{
// Returns n-th element of the series
static int series(int n)
{
return (8 * n * n) + 1;
}
// driver program to test the above
// function
public static void main(String args[])
{
int n = 5;
System.out.println(series(n));
}
}
/*This code is contributed by Nikita Tiwari.*/
Python3
# Python Program to find n-th element
# in the series 9, 33, 73, 128...
# Returns n-th element of the series
def series(n):
print (( 8 * n ** 2) + 1)
# Driver Code
series(5)
# This code is contributed by Abhishek Agrawal.
C#
// C# program to find n-th element in the
// series 9, 33, 73, 128..
using System;
class GFG {
// Returns n-th element of the series
static int series(int n)
{
return (8 * n * n) + 1;
}
// driver function
public static void Main()
{
int n = 5;
Console.WriteLine(series(n));
}
}
/*This code is contributed by vt_m.*/
PHP
Javascript
输出:
201