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!!!

1

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.