Smallest prime factor of a large number (using BigInteger)
Factors to consider


If number 2 is not a factor, then all large even numbers will not be factors. Therefore, checking only the odd numbers is sufficient.
For integers i x j = n, if i is larger than the square root of n, then j has to be smaller than the square root of n (Therefore, already checked). Hence, numbers higher than the square root of n do not have to be checked as candidates for prime factors.

private static BigInteger smallestPrimeFactor(BigInteger n) {
    BigInteger two = new BigInteger("2");
    if (n.mod(two).compareTo(BigInteger.ZERO) == 0) {
        return two;
    }

    for (BigInteger i = new BigInteger("3"); n.compareTo(i.multiply(i)) &gt;= 0; i = i.add(two)) {         
        if (n.mod(i).compareTo(BigInteger.ZERO) == 0) {
            return i;
        }
    }
    return n;
}