1.素数判定
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
int limit = (int)Math.sqrt(n) + 1;
for (int i = 3; i <= limit; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
2.分解质素数
public static List<Integer> getPrimeFactor(int n) {
if (n <= 1) {
return new ArrayList<Integer>();
}
List<Integer> factors = new ArrayList<Integer>();
int number = n;
int factor = 2;
while (factor <= number) {
if (number % factor == 0) {
factors.add(factor);
number /= factor;
} else {
factor++;// next prime factor?
}
}
return factors;
}