原文:
给定一个数字 n ,任务是找到 n 个数字,这样它们的和就是一个。
示例:
输入: n = 3 输出: 1 7 19 解释: 数之和= 1 7 19 = 27, 是 3 = > 3 3 = 27 的完美立方
输入: n = 4 输出: 1 7 19 37 数之和= 1 7 19 37 = 64, 是 4 = > 4 3 = 64 的完美立方
方法: 在考虑 后,该数字表示:
第一个 n 个中心六边形数的和是 n 的完美立方
所以从中心六边形数开始,级数的前 n 项将给出 n 个数,这样它们的和就是一个完美的立方体。
例如:
for n = 1,
centered hexagonal series = 1
and 13 = 1
hence, {1} is the required n number
for n = 2,
centered hexagonal series = 1, 7
and 23 = 1 7 = 8
hence, {1, 7} are the required n number
for n = 3,
centered hexagonal series = 1, 7, 19
and 33 = 1 7 19 = 27
hence, {1, 7, 19} are the required n number
.
.
and so on.
因此,可以说打印中心六边形数字的前 n 项将给出所需的 n 个数字。 同样,中心六边形数字的第 n 项是:
算法:
- 用一个循环变量(比如说 i )从 1 到 n 迭代一个,对于每个迭代–
- 使用公式 3i(i-1) 1 求出中心六边形数的第 n 个项。
- 在数组中追加第 i 个项。
下面是上述方法的实现:
c
// c implementation to find the n
// numbers such that their
// sum is a perfect cube
#include
using namespace std;
// function to find the n
// numbers such that their
// sum is a perfect cube
void findnumbers(int n)
{
int i = 1;
// loop to find the ith term
// of the centered hexagonal number
while (i <= n) {
cout << (3 * i * (i - 1) 1)
<< " ";
i ;
}
}
// driver code
int main()
{
int n = 4;
// function call
findnumbers(n);
}
java 语言(一种计算机语言,尤用于创建网站)
// java implementation to find the n
// numbers such that their
// sum is a perfect cube
class gfg
{
// function to find the n
// numbers such that their
// sum is a perfect cube
static void findnumbers(int n)
{
int i = 1;
// loop to find the ith term
// of the centered hexagonal number
while (i <= n)
{
system.out.print((3 * i * (i - 1) 1) " ");
i ;
}
}
// driver code
public static void main (string[] args)
{
int n = 4;
// function call
findnumbers(n);
}
}
// this code is contributed by ankitrai01
c
// c# implementation to find the n
// numbers such that their
// sum is a perfect cube
using system;
public class gfg
{
// function to find the n
// numbers such that their
// sum is a perfect cube
static void findnumbers(int n)
{
int i = 1;
// loop to find the ith term
// of the centered hexagonal number
while (i <= n)
{
console.write((3 * i * (i - 1) 1) " ");
i ;
}
}
// driver code
public static void main()
{
int n = 4;
// function call
findnumbers(n);
}
}
// this code is contributed by ankitrai01
python 3
# python3 implementation to find the n
# numbers such that their
# sum is a perfect cube
# function to find the n
# numbers such that their
# sum is a perfect cube
def findnumbers(n):
i = 1
# loop to find the ith term
# of the centered hexagonal number
while (i <= n):
print((3 * i * (i - 1) 1), end=" ")
i = 1
# driver code
n = 4
# function call
findnumbers(n)
# this code is contributed by mohit kumar 29
java 描述语言
output:
1 7 19 37
性能分析:
- 时间复杂度:和上面的方法一样,我们正在寻找所有的 n centered 六边形数,所以需要 o(n) 。
- 辅助空间:和上面的方法一样,没有使用额外的空间,所以使用的辅助空间将是 o(1)
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处