Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
class PrimeFactorization {
private final String dividend;
PrimeFactorization(String dividend) {
this.dividend = dividend;
}
List<BigInteger> computePrimeFactor() {
BigInteger dividend = new BigInteger(this.dividend);
BigInteger divisor = BigInteger.valueOf(2L);
// dividendがdivisor以下の場合に例外を投げる
if (dividend.compareTo(divisor) == -1) {
throw new IllegalStateException();
}
// 除数を2から1ずつ増やしていき、素因数分解をする
List<BigInteger> list = new ArrayList<>();
while (dividend.compareTo(BigInteger.ONE) != 0) {
while (dividend.remainder(divisor).equals(BigInteger.ZERO)) {
dividend = dividend.divide(divisor);
list.add(divisor);
}
divisor = divisor.add(BigInteger.ONE);
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.