Java 写函数,它是素因子的返回数组
我有一个函数,它返回一个数的素数因子,但当我初始化int数组时,我设置了大小。因此结果包含不必要的零。如何返回没有零的结果数组,或者如何初始化数组的适用大小?我没有使用列表Java 写函数,它是素因子的返回数组,java,Java,我有一个函数,它返回一个数的素数因子,但当我初始化int数组时,我设置了大小。因此结果包含不必要的零。如何返回没有零的结果数组,或者如何初始化数组的适用大小?我没有使用列表 public static int[] encodeNumber(int n){ int i; int j = 0; int[] prime_factors = new int[j]; if(n <= 1) return null; for
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;
}
公共静态int[]编码编号(int n){
int i;
int j=0;
int[]素数因子=新的int[j];
如果(n分配尽可能多的因素(32个听起来很合适),然后使用Arrays.copyOf()
以实际限制切断数组:
return Arrays.copyOf(prime_factors, j);
这里有一个快速的方法来解决我最近解决的主要因素问题。我不认为它是原创的,但我自己创建了它。实际上,我必须在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;
}
publicstaticint[]getPrimeFactors(finalinti){
返回getPrimeFactors1(i,0,2);
}
私有静态int[]getPrimeFactors1(int number,final int numberOfFactorsFound,final int startAt){
如果(数字0){
toReturn[currentIndex+--NumberOfRepeations]=currentFactor;
}
回归回归;
}