Java 中的煎饼数

13 May 2025 | 5 分钟阅读

在本节中,我们将讨论什么是煎饼数,并使用不同的方法创建Java 程序来查找煎饼数。煎饼数程序经常在 Java 编码面试和学术中出现。

煎饼数

煎饼数 Pj 表示使用 j 次切割可以将圆形或煎饼分割成的最大块数。煎饼数也称为懒人割饼数,更正式的名称是中心多边形数

在数学上,煎饼数 Pj 表示为

Pancake Number in Java

下图显示了 j = 0 到 j = 5 的煎饼数。

Pancake Number in Java

煎饼数 Java 程序

以下代码显示了使用上述数学公式实现的煎饼数。

文件名: PancakeNumberExample.java

输出

For j = 0, the pancake number is: 1
For j = 1, the pancake number is: 2
For j = 2, the pancake number is: 4
For j = 3, the pancake number is: 7
For j = 4, the pancake number is: 11
For j = 5, the pancake number is: 16
For j = 6, the pancake number is: 22
For j = 7, the pancake number is: 29
For j = 8, the pancake number is: 37
For j = 9, the pancake number is: 46

使用组合计算煎饼数

煎饼数也可以通过组合来获得。使用组合,煎饼数定义为

Pj = 0C0 = 1,对于 j = 0

Pj = 1C0 + 1C1 = 1 + 1 = 2,对于 j = 1

对于 j >= 2,

Pj = jC0 + jC1 + jC2

因此,

对于 j = 2,

P2 = 2C0 + 2C1 + 2C2 = 1 + 2 + 1 = 4

对于 j = 3,

P3 = 3C0 + 3C1 + 3C2 = 1 + 3 + 3 = 7

对于 j = 4,

P4 = 4C0 + 4C1 + 4C2 = 1 + 4 + 6 = 11

对于 j = 5,

P5 = 5C0 + 5C1 + 5C2 = 1 + 5 + 10 = 16

将上述公式合并,对于 j = 0, 1, 和 >= 2,我们得到

Pj = 1,对于 j = 0,以及

Pj = j + 1C2 + 1,对于 j >= 1

因此,

P0 = 1

P1 = 1 + 1C2 + 1 = 2C2 + 1 = 1 + 1 = 2

P2 = 2 + 1C2 + 1 = 3C2 + 1 = 3 + 1 = 4

P3 = 3 + 1C2 + 1 = 4C2 + 1 = 6 + 1 = 7

煎饼数:迭代方法

让我们来实现上述组合公式来计算煎饼数。

文件名: PancakeNumberExample1.java

输出

For j = 0, the pancake number is: 1
For j = 1, the pancake number is: 2
For j = 2, the pancake number is: 4
For j = 3, the pancake number is: 7
For j = 4, the pancake number is: 11
For j = 5, the pancake number is: 16
For j = 6, the pancake number is: 22
For j = 7, the pancake number is: 29
For j = 8, the pancake number is: 37
For j = 9, the pancake number is: 46

煎饼数:递归方法

组合公式也可以通过递归来实现。下面的程序显示了这一点。

文件名: PancakeNumberExample2.java

输出

For j = 0, the pancake number is: 1
For j = 1, the pancake number is: 2
For j = 2, the pancake number is: 4
For j = 3, the pancake number is: 7
For j = 4, the pancake number is: 11
For j = 5, the pancake number is: 16
For j = 6, the pancake number is: 22
For j = 7, the pancake number is: 29
For j = 8, the pancake number is: 37
For j = 9, the pancake number is: 46