Java 中的 Pernicious 数

17 Mar 2025 | 4 分钟阅读

在本节中,我们将讨论什么是无害数,并创建 Java 程序 来检查给定数字是否为无害数无害数程序经常在 Java 编码面试和学术界中出现。

无害数

如果一个数字的二进制表示中 1 的总数是素数,则该数字称为无害数。无害数始终是正整数。

无害数示例

1 不是无害数。这是因为 1 的二进制表示是 1,而 1 不是素数。

2 不是无害数。这是因为 2 的二进制表示是 1 0。2 的二进制表示中 1 的总数是 1,而 1 不是素数。

3 是一个无害数。这是因为 3 的二进制表示是 1 0 1。3 的二进制表示中 1 的总数是 2,而 2 是素数。

4 不是无害数。这是因为 4 的二进制表示是 1 0 0。4 的二进制表示中 1 的总数是 1,而 1 不是素数。

5 是一个无害数。这是因为 5 的二进制表示是 1 0 1。5 的二进制表示中 1 的总数是 2,而 2 是素数。

查找无害数的步骤

步骤 1:取一个数字,通过不断除以 2 来找到它的二进制表示。

步骤 2:将数字的二进制表示存储在数组中。

步骤 3:取一个计数器并将其初始化为 0。

步骤 4:使用循环遍历数组的每个元素。如果元素为 1,则计数器值增加 1;否则,不增加。

步骤 5:检查计数器的值,并找出计数器是奇数还是偶数。

步骤 6:如果值为奇数,则步骤 1 中取的数字是无害数;否则,不是。

无害数 Java 程序

下面的示例将使用循环,根据上述步骤查找无害数。

文件名:PerniciousNumberExample1.java

输出

1 is not the pernicious number.
2 is not the pernicious number.
3 is the pernicious number.
4 is not the pernicious number.
5 is the pernicious number.
6 is the pernicious number.
7 is the pernicious number.
8 is not the pernicious number.
9 is the pernicious number.
10 is the pernicious number.
11 is the pernicious number.
12 is the pernicious number.
13 is the pernicious number.
14 is the pernicious number.
15 is not the pernicious number.
16 is not the pernicious number.
17 is the pernicious number.
18 is the pernicious number.
19 is the pernicious number.
20 is the pernicious number.