求序列 1^3/1+(1^3+2^3)/(1+3)+(1^3+2^3+3^3)/(1+3+5)+ 的第 N 项…
给定一个正整数N 。任务是找到系列的第 N项:
例子:
Input: N = 2
Output: 2.25
Input: N = 3
Output: 4
方法:
从给定的系列中,找到第 N项的公式:
1st term = 1^3/1 = 1/1 = 1
2nd term = (1^3+2^3)/(1+3) = (1+8)/4 = 9/4 = 2.25
3rd term = (1^3+2^3+3^3)/(1+3+5) = (1+8+27)/9 = 4
4th term = (1^3+2^3+3^3+4^3)/(1+3+5+7) = (1+8+27+64)/16 = 6.25
.
.
Nth term = ((N*(N+1)/2)^2)/(N*(2+(N-1)*2)/2) = (N+1)^2/4 = (N^2+2N+1)/4
推导:
For the series-
Nth term can be written as-
Here,
and 1+3+5+….+(2*N-1) are in A.P.
Rewriting the above equation using the formula for A.P. as-
给定序列的第 N项可以概括为:
插图:
Input: N = 2
Output: 2.25
Explanation: (1^3+2^3)/(1+3)
= (1 +8)/4
= 9/4
= 2.25
下面是上述问题的实现:
C++
// C++ program to find N-th term
// in the series
#include
using namespace std;
// Function to find N-th term
// in the series
double nthTerm(int N)
{
return (pow(N, 2) +
2 * N + 1) / 4;
}
// Driver Code
int main()
{
// Get the value of N
int N = 5;
cout << nthTerm(N);
return 0;
}
Java
// Java code for the above approach
import java.io.*;
class GFG {
// Function to find N-th term
// in the series
static double nthTerm(int N)
{
return (Math.pow(N, 2) + 2 * N + 1) / 4;
}
public static void main(String[] args)
{
// Get the value of N
int N = 5;
System.out.println(nthTerm(N));
}
}
// This code is contributed by Potta Lokesh
Python
# python 3 program for the above approach
import sys
# Function to find N-th term
# in the series
def nthTerm(N):
return (pow(N, 2) + 2 * N + 1) / 4
# Driver Code
if __name__ == "__main__":
N = 5
print(nthTerm(N))
# This code is contributed by hrithikgarg03188
C#
// C# program to find N-th term
// in the series
using System;
class GFG
{
// Function to find N-th term
// in the series
static double nthTerm(int N)
{
return (Math.Pow(N, 2) +
2 * N + 1) / 4;
}
// Driver Code
public static void Main()
{
// Get the value of N
int N = 5;
Console.Write(nthTerm(N));
}
}
// This code is contributed by Samim Hosdsain Mondal.
Javascript
9
时间复杂度: O(1)
辅助空间: O(1)