1

我有一个函数,它返回一个数字的素数,但是当我初始化 int 数组时我设置了大小。所以结果包含不必要的。如何返回不带零的结果数组或如何初始化数组适用的大小?我没有使用列表

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;
    }

谢谢!!!

4

2 回答 2

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;
}
于 2012-09-10T04:09:22.960 回答
0

分配您认为该数字可能具有的尽可能多的因子(32 听起来不错),然后用于Arrays.copyOf()在实际限制处截断数组:

return Arrays.copyOf(prime_factors, j);
于 2012-06-25T13:57:23.087 回答