C++程序 找出序列9、23、45、75、113…的第N项
给定一个数N,任务是在给定的序列中找到第N项:
9, 23, 45, 75, 113, 159......
例子:
输入: 4
输出: 113
解释:
对于N = 4
第N项 = ( 2 * N + 3 )( 2 * N + 3 ) – 2 * N
= ( 2 * 4 + 3 )( 2 * 4 + 3 ) – 2 * 4
= 113
输入: 10
输出: 509
方法:
所给序列的第N项可推广如下:
序列的第N项 : ( 2 * N + 3 )*( 2 * N + 3 ) – 2 * N
下面是实现以上问题的程序:
程序:
// CPP program to find N-th term of the series:
// 9, 23, 45, 75, 113...
#include <iostream>
using namespace std;
// calculate Nth term of series
int nthTerm(int N)
{
return (2 * N + 3) * (2 * N + 3) - 2 * N;
}
// Driver Function
int main()
{
// Get the value of N
int N = 4;
// Find the Nth term
// and print it
cout << nthTerm(N);
return 0;
}
// Java program to find
// N-th term of the series:
// 9, 23, 45, 75, 113...
class GFG
{
// calculate Nth term of series
static int nthTerm(int N)
{
return (2 * N + 3) *
(2 * N + 3) - 2 * N;
}
// Driver code
public static void main(String[] args)
{
// Get the value of N
int N = 4;
// Find the Nth term
// and print it
System.out.println(nthTerm(N));
}
}
// This code is contributed by Bilal
# Python program to find
# N-th term of the series:
# 9, 23, 45, 75, 113...
def nthTerm(N):
# calculate Nth term of series
return ((2 * N + 3) *
(2 * N + 3) - 2 * N);
# Driver Code
# Get the value of N
n = 4
# Find the Nth term
# and print it
print(nthTerm(n))
# This code is contributed by Bilal
// C# program to find
// N-th term of the series:
// 9, 23, 45, 75, 113...
using System;
class GFG
{
// calculate Nth term of series
static int nthTerm(int N)
{
return (2 * N + 3) *
(2 * N + 3) - 2 * N;
}
// Driver code
public static void Main()
{
// Get the value of N
int N = 4;
// Find the Nth term
// and print it
Console.WriteLine(nthTerm(N));
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
<?php
// PHP program to find
// N-th term of the series:
// 9, 23, 45, 75, 113...
// calculate Nth term of series
function nthTerm(N)
{
return (2 *N + 3) *
(2 * N + 3) - 2 *N;
}
// Driver Code
// Get the value of N
N = 4;
// Find the Nth term
// and print it
echo nthTerm(N);
// This code is contributed by Raj
?>
<script>
// JavaScript program to find N-th term of the series:
// 9, 23, 45, 75, 113...
// calculate Nth term of series
function nthTerm( N)
{
return (2 * N + 3) * (2 * N + 3) - 2 * N;
}
// Driver Function
// get the value of N
let N = 4;
// Calculate and print the Nth term
document.write( nthTerm(N));
// This code is contributed by todaysgaurav
</script>
输出结果:
113
时间复杂度: O(1)
空间复杂度: : O(1)因为使用了常量变量