原文:
给定一个数字 n ,任务是打印系列 6、28、66、120、190、276 的前 n 个术语,以此类推。 例:
输入:n = 10 t3】输出:6 28 66 120 190 276 378 496 630 780 t6】输入:n = 4 t9】输出: 6 28 66 120
方法:要解决上述问题,我们必须观察以下模式:
通式如下: k *(2 * k–1),其中,最初 k = 2
下面是上述方法的实现:
c
// c program for the above approach
#include
using namespace std;
// function to print the series
void printseries(int n)
{
// initialise the value of k with 2
int k = 2;
// iterate from 1 to n
for (int i = 0; i < n; i ) {
// print each number
cout << (k * (2 * k - 1))
<< " ";
// increment the value of
// k by 2 for next number
k = 2;
}
cout << endl;
}
// driver code
int main()
{
// given number n
int n = 12;
// function call
printseries(n);
return 0;
}
java 语言(一种计算机语言,尤用于创建网站)
// java program for the above approach
class gfg{
// function to print the series
static void printseries(int n)
{
// initialise the value of k with 2
int k = 2;
// iterate from 1 to n
for (int i = 0; i < n; i )
{
// print each number
system.out.print(k * (2 * k - 1) " ");
// increment the value of
// k by 2 for next number
k = 2;
}
system.out.println();
}
// driver code
public static void main(string args[])
{
// given number n
int n = 12;
// function call
printseries(n);
}
}
// this code is contributed by shivaniisnghss2110
python 3
# python3 program for the above approach
# function to print the series
def printseries(n):
# initialise the value of k with 2
k = 2
# iterate from 1 to n
for i in range(0, n):
# print each number
print(k * (2 * k - 1), end = ' ')
# increment the value of
# k by 2 for next number
k = k 2
# driver code
# given number
n = 12
# function call
printseries(n)
# this code is contributed by poulami21ghosh
c
// c# program for the above approach
using system;
class gfg{
// function to print the series
static void printseries(int n)
{
// initialise the value of k with 2
int k = 2;
// iterate from 1 to n
for(int i = 0; i < n; i )
{
// print each number
console.write(k * (2 * k - 1) " ");
// increment the value of
// k by 2 for next number
k = 2;
}
console.writeline();
}
// driver code
public static void main()
{
// given number n
int n = 12;
// function call
printseries(n);
}
}
// this code is contributed by sanjoy_62
java 描述语言
output:
6 28 66 120 190 276 378 496 630 780 946 1128
时间复杂度:o(n) t5】辅助空间: o(1)
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处