1

I have a function it returns prime factors of a number but when I initialize int array I set size.So the result consists unnecessary zeros.How can I return result array without zeros or how can I initialize array applicable size? I am not using Lists

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

Thanx!!!

Tim
  • 35,413
  • 11
  • 95
  • 121
  • possible duplicate of [Delete item from array and shrink array](http://stackoverflow.com/questions/4870188/delete-item-from-array-and-shrink-array) – assylias Jun 25 '12 at 13:56

2 Answers2

2

Here is a quick way to get about the prime factors problem that I recently worked out. I don't claim it is original, but I did create it on my own. Actually had to do this in C, where I wanted to malloc only once.

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

Allocate as many factors as you think the number may have (32 sounds like a good candidate), and then use Arrays.copyOf() to cut off the array at the actual limit:

return Arrays.copyOf(prime_factors, j);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523