Java 中的宏观数

2025 年 5 月 13 日 | 阅读 6 分钟

在本教程中,我们将学习Java 中的充裕数

充裕数

充裕数是指至少有两位数,并且当数字的左部分与右部分相加时,总是会生成一个素数。数字的左部分和右部分可以大小不限,但不能为零。

充裕数示例

以数字 359794 为例。它的左部分和右部分在下表中列出。

左部分右部分
359794
359794
359794
359794
359794

现在,我们检查左部分和右部分的加法。

3 + 59794 = 59797

35 + 9794 = 9829

359 + 794 = 1153

3597 + 94 = 3691

35979 + 4 = 35983

数字 59797、9829、1153、3691 和 35983 都是素数。因此,359794 是一个充裕数。

让我们再取数字 200。数字 100 的左部分和右部分是

左部分右部分
200
200

现在左部分和右部分的和是

2 + 00 = 2,20 + 0 = 20。

因此,我们得到两个数字,一个是 2,另一个是 20,其中 2 是素数,20 不是素数。因此,我们至少得到一个不是素数的数字。因此,200 不是充裕数。

查找充裕数的步骤

以下是查找充裕数所涉及的步骤。

步骤 1:取一个数字(假设数字为 num),并将其转换为字符串。

步骤 2:遍历字符串,获取字符串的所有左部分和右部分。

步骤 3:将字符串的每一部分(左部分和右部分)都转换为整数。

步骤 4:生成左右部分的和。

步骤 5:检查步骤 4 中生成的每个和(是否为素数)。

步骤 6:如果每个生成的和都是素数,则数字 num 是充裕数;否则不是。

Java 充裕数程序

迭代方法

以下程序使用迭代方法,根据上述步骤检查充裕数。

文件名:MagnanimousNumberExamples.java

输出

10 is not the magnanimous number.
11 is the magnanimous number.
12 is the magnanimous number.
13 is not the magnanimous number.
14 is the magnanimous number.
15 is not the magnanimous number.
16 is the magnanimous number.
17 is not the magnanimous number.
18 is not the magnanimous number.
19 is not the magnanimous number.
20 is the magnanimous number.

递归方法

以下程序使用递归方法检查充裕数。

文件名:MagnanimousNumberExample1.java

输出

10 is not the magnanimous number.
11 is the magnanimous number.
12 is the magnanimous number.
13 is not the magnanimous number.
14 is the magnanimous number.
15 is not the magnanimous number.
16 is the magnanimous number.
17 is not the magnanimous number.
18 is not the magnanimous number.
19 is not the magnanimous number.
20 is the magnanimous number.