2012-06-25 27 views
1

我有一个函数它返回一个数字的素数因子,但是当我初始化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

可能重复的[从数组和缩小数组中删除项目](http://stackoverflow.com/questions/4870188/delete-item-from-array-and-shrink-array) – assylias

回答

0

分配尽可能多的因素,您认为这个数字可能有(32个听起来是个不错的人选),然后用Arrays.copyOf()在实际的限制,切断阵列:

return Arrays.copyOf(prime_factors, j); 
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; 
}