我有一个函数它返回一个数字的素因子但是当我初始化int数组时我设置size.So结果包含不必要的零。如何返回没有零的结果数组或者我怎么能初始化数组适用的大小?我没有使用列表
public static int[] encodeNumber(int n){
int i;
int j = 0;
int[] prime_factors = new int[j];
if(n <= 1) return null;
for(i = 2; i <= n; i++){
if(n % i == 0){
n /= i;
prime_factors[j] = i;
i--;
j++;
}
}
return prime_factors;
}
感谢名单!!!
答案 0 :(得分:2)
这是一个快速了解我最近解决的主要因素问题的方法。我并不认为它是原创的,但我确实是自己创造的。实际上不得不在C中这样做,我只想在malloc上做一次。
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;
}
答案 1 :(得分:0)
分配尽可能多的因素,你认为这个数字可能有多少(32个听起来像是一个好的候选者),然后使用Arrays.copyOf()
来切断实际限制的数组:
return Arrays.copyOf(prime_factors, j);