これは、私が最近取り組んだ素因数問題について簡単に理解する方法です。オリジナルとは言いませんが、自分で作ったものです。実際にはこれをCで行う必要があり、mallocを1回だけにしたかったのです。
public static int[] getPrimeFactors(final int i) {
return getPrimeFactors1(i, 0, 2);
}
private static int[] getPrimeFactors1(int number, final int numberOfFactorsFound, final int startAt) {
if (number <= 1) { return new int[numberOfFactorsFound]; }
if (isPrime(number)) {
final int[] toReturn = new int[numberOfFactorsFound + 1];
toReturn[numberOfFactorsFound] = number;
return toReturn;
}
final int[] toReturn;
int currentFactor = startAt;
final int currentIndex = numberOfFactorsFound;
int numberOfRepeatations = 0;
// we can loop unbounded by the currentFactor, because
// All non prime numbers can be represented as product of primes!
while (!(isPrime(currentFactor) && number % currentFactor == 0)) {
currentFactor += currentFactor == 2 ? 1 : 2;
}
while (number % currentFactor == 0) {
number /= currentFactor;
numberOfRepeatations++;
}
toReturn = getPrimeFactors1(number, currentIndex + numberOfRepeatations, currentFactor + (currentFactor == 2 ? 1 : 2));
while (numberOfRepeatations > 0) {
toReturn[currentIndex + --numberOfRepeatations] = currentFactor;
}
return toReturn;
}