查找系列5、13、25、41、61的第n项…

给定一个数字N。任务是编写一个程序,在下面的系列中查找第N项:

null
5, 13, 25, 41, 61...

例如:

Input : 3Output : 25For N = 3Nth term = 3*3 + (3+1)*(3+1)         = 25Input : 5Output : 61

仔细观察,给定序列的第n项可概括为:

Nth term = N2 + (N+1)2

以下是上述方法的实施情况:

C++

// CPP program to find N-th term of the series:
// 5, 13, 25, 41, 61...
#include <iostream>
using namespace std;
// calculate Nth term of series
int nthTerm( int N)
{
return N * N + (N + 1) * (N + 1);
}
// Driver Function
int main()
{
int N = 3;
cout << nthTerm(N);
return 0;
}


JAVA

// Java program to calculate Nth term of
// the series: 5, 13, 25, 41, 61...
import java.io.*;
class Nth {
public static int nthTerm( int N)
{
// By using above formula
return N * N + (N + 1 ) * (N + 1 );
}
public static void main(String[] args)
{
int N = 3 ; // Nth term is 25
// call and print Nth term
System.out.println(nthTerm(N));
}
}


Python 3

# Python 3 program to find
# N-th term of the series:
# 5, 13, 25, 41, 61...
# Function to calculate
# Nth term of series
def nthTerm(N) :
return N * N + (N + 1 ) * (N + 1 )
# Driver Code
if __name__ = = "__main__" :
N = 3
# function calling
print (nthTerm(N))
# This code is contributed
# by ANKITRAI1


C#

// C# program to calculate Nth term of
// the series: 5, 13, 25, 41, 61...
using System;
class GFG
{
public static int nthTerm( int N)
{
// By using above formula
return N * N + (N + 1) * (N + 1);
}
// Driver Code
public static void Main()
{
int N = 3; // Nth term is 25
// call and print Nth term
Console.Write(nthTerm(N));
}
}
// This code is contributed
// by ChitraNayal


PHP

<?php
// PHP program to find N-th
// term of the series:
// 5, 13, 25, 41, 61...
// calculate Nth term of series
function nthTerm( $N )
{
return $N * $N + ( $N + 1) *
( $N + 1);
}
// Driver Code
$N = 3;
echo nthTerm( $N );
// This code is contributed
// by ChitraNayal
?>


Javascript

<script>
// JavaScript program to find N-th term of the series:
// 5, 13, 25, 41, 61...
// calculate Nth term of series
function nthTerm( N)
{
return N * N + (N + 1) * (N + 1);
}
// Driver Function
let N = 3;
document.write(nthTerm(N));
// This code contributed by Rajput-Ji
</script>


输出:

25

时间复杂性: O(1)

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享