【发布时间】:2012-04-25 17:01:53
【问题描述】:
我正在尝试用 Java 编写一个函数,该函数将返回特定数字所具有的因子数。
应考虑以下限制。
- 应该用 BigInteger 来完成
- 不允许存储以前生成的数字,因此需要更多的处理和更少的内存。(不能像this 那样使用“阿特金筛子”)
- 可以忽略负数。
这是我目前所拥有的,但速度非常慢。
public static int getNumberOfFactors(BigInteger number) {
// If the number is 1
int numberOfFactors = 1;
if (number.compareTo(BigInteger.ONE) <= 0) {
return numberOfFactors;
}
BigInteger boundry = number.divide(new BigInteger("2"));
BigInteger counter = new BigInteger("2");
while (counter.compareTo(boundry) <= 0) {
if (number.mod(counter).compareTo(BigInteger.ZERO) == 0) {
numberOfFactors++;
}
counter = counter.add(BigInteger.ONE);
}
// For the number it self
numberOfFactors++;
return numberOfFactors;
}
【问题讨论】:
-
如果有重复的因素,这也会失败,例如2*2*2 将返回 2(1 代表 2,1 代表 4)
-
@PeterLawrey 不正确 - 他正在迭代所有因素,从不进行除法。
-
因式分解可能非常慢,以至于它被用于某些加密算法中。
-
叫Euler's totient function,9000是对的,不是简单的问题。
-
@PeterLawrey 这个问题从来没有说过它应该只返回素数的数量。我假设从问题的措辞方式来看,8 的因子数应该返回 4 (1, 2, 4, 8)