不知道你爲什麼要返回一個字符串!
這適用於我。需要注意的是它比較i
,每次圍繞n/i
和n = n/i
:
// Memoization of factors.
static Map<BigInteger, List<BigInteger>> factors = new HashMap<>();
private static final BigInteger TWO = BigInteger.ONE.add(BigInteger.ONE);
public static List<BigInteger> factors(BigInteger n, boolean duplicates) {
// Have we done this one before?
List<BigInteger> f = factors.get(n);
if (f == null) {
// Start empty.
f = new ArrayList<>();
// Check for duplicates.
BigInteger last = BigInteger.ZERO;
// Limit the range as far as possible.
for (BigInteger i = TWO; i.compareTo(n.divide(i)) <= 0; i = i.add(BigInteger.ONE)) {
// Can have multiple copies of the same factor.
while (n.mod(i).equals(BigInteger.ZERO)) {
if (duplicates || !i.equals(last)) {
f.add(i);
last = i;
}
// Remove that factor.
n = n.divide(i);
}
}
if (n.compareTo(BigInteger.ONE) > 0) {
// Could be a residue.
if (duplicates || n != last) {
f.add(n);
}
}
// Memoize.
factors.put(n, f);
}
return f;
}
這如果是沒用 '如果(monster.mod(二).equals(0)); - (?)' >刪除分號 *如果您檢查分割性2,您應該測試對於3,5 ...然後 * for/while嵌套循環有點難以理解,您應該用遞歸樣式重寫您的函數。 *我會積累在例如一個ArrayList,但這是一個風格問題:-) –
您可以使用'Stringbuilder'來代替字符串。 [Class StringBuilder](http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html) – Smit
@Gyro它比無用的更糟糕,它使整個算法無效。 – Arend