Powerful Number in Java

2025 年 5 月 8 日 | 阅读 5 分钟

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

强大数

如果一个数 X 的所有质因数的平方都能整除 X,则称 X 为强大数

换句话说,X 的所有质因数的平方都必须是 X 的因子。此外,X 必须是 l2m3 的形式,其中 l 和 m 是正数。数学上,

如果 X = l2m3,l > 0,m > 0,且 X % P = 0,X % (P * P) = 0,其中 P 是一个质数,并且对于 P 作为 X 的因子的每个值都满足给定条件,那么我们可以说 X 是一个强大数。

查找强大数的步骤

步骤 1:将一个数字赋给变量。

步骤 2:找到给定数字的质因数。

步骤 3:将这些因子存储在一个列表中。

步骤 4:遍历列表中存在的这些因子,并找到这些因子的平方。

步骤 5:检查列表中存在的每个因子的平方是否能整除给定的数字。

如果任何一个因子的平方不能整除给定的数字,那么给定的数字就不是强大数;否则,就是强大数。

强大数示例

给定 X = 10

X 的因子:2, 5(质因数)

将质因数平方,我们得到 2 * 2 = 4,以及 5 * 5 = 25。

现在,我们分别用 4 和 25 除 10。

10 % 4 = 2,10 % 25 = 10。因此,我们看到余数不为零。所以,数字10 不是强大数。

给定 X = 36

X 的因子:2, 3(质因数)

质因数的平方,我们得到 2 * 2 = 4,以及 3 * 3 = 9。

分别用 4 和 9 除 36,我们得到

36 % 4 = 0,36 % 9 = 0。因此,我们看到在所有情况下余数都为零。此外,36 可以写成 2232,其中 2 > 0 且 3 > 0。因此,数字36强大数

Powerful Number in Java

上面的图表显示 1, 4, 8, 和 9 是强大数。

注意:质数永远不可能成为强大数,因为该数字的质因数就是该数字本身,而该数字的平方永远不能整除该数字本身。

例如,5 是一个质数。因此,它的质因数也是 5。同时,5 * 5 = 25。现在,5 % 25 = 5,不等于 0。因此,5 不是强大数。

强大数 Java 程序

观察以下检查 1 到 20 之间的强大数的 Java 程序。

文件名:PowerfulNumberExample.java

输出

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

说明:对于 1 到 20 之间的每个数字,通过 for 循环调用方法 isPowerfulNo()。对于每个数字,创建一个向量 primeFactors 来存储其质因数。然后,我们检查向量 primeFactors 中存在的每个数字的平方是否能整除该数字。如果向量 primeFactors 中所有数字的平方都能完全整除该数字,则该数字是强大数;否则,不是。