原文:
给定一个整数 n ,任务是打印 n 个数字,这样它们的和就是一个完美的正方形。 例:
输入: n = 3 输出: 1 3 5 1 3 5 = 9 = 3 2
输入: n = 4 输出:1 3 5 7 1 3 5 7 = 16 = 42
逼近:第一个 n 个奇数的和总是一个完美的平方。因此,我们将打印第一个 n 奇数作为输出。 以下是上述方法的实现:
c
// c implementation of the approach
#include
using namespace std;
// function to print n numbers such that
// their sum is a perfect square
void findnumbers(int n)
{
int i = 1;
while (i <= n) {
// print ith odd number
cout << ((2 * i) - 1) << " ";
i ;
}
}
// driver code
int main()
{
int n = 3;
findnumbers(n);
}
java 语言(一种计算机语言,尤用于创建网站)
// java implementation of the approach
class gfg {
// function to print n numbers such that
// their sum is a perfect square
static void findnumbers(int n)
{
int i = 1;
while (i <= n) {
// print ith odd number
system.out.print(((2 * i) - 1) " ");
i ;
}
}
// driver code
public static void main(string args[])
{
int n = 3;
findnumbers(n);
}
}
python 3
# python3 implementation of the approach
# function to print n numbers such that
# their sum is a perfect square
def findnumber(n):
i = 1
while i <= n:
# print ith odd number
print((2 * i) - 1, end = " ")
i = 1
# driver code
n = 3
findnumber(n)
# this code is contributed by shrikant13
c
// c# implementation of the approach
using system;
public class gfg {
// function to print n numbers such that
// their sum is a perfect square
public static void findnumbers(int n)
{
int i = 1;
while (i <= n) {
// print ith odd number
console.write(((2 * i) - 1) " ");
i ;
}
}
// driver code
public static void main(string[] args)
{
int n = 3;
findnumbers(n);
}
}
// this code is contributed by shrikant13
服务器端编程语言(professional hypertext preprocessor 的缩写)
java 描述语言
output
1 3 5
时间复杂度: o(n)
辅助空间: o(1)
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处