0

I am writing a program to find perfect numbers. The first step in doing this is to find all of the factors of a number. I need some code to find the factor of a number and save the factors to an array (NOT print the numbers). This is what I have so far, but it returns a NullPointerException:

public static int[] getFactors(int number) {
    int factorNumber = 1;
    int varArrayStoreID = 0;
    int[] factors = null;

    while(factorNumber <= number){
        if(number % factorNumber == 0){
            varArrayStoreID = varArrayStoreID + 1;
            factors[varArrayStoreID] = factorNumber;
        }
        factorNumber++;
    }

    return factors;
}

Thanks.

Wilson Gramer
  • 702
  • 8
  • 23

1 Answers1

2

The problem is that you have to initialize your Array before you can try and add anything to it. This doesn't really work in your case since you do not know how many factors a number will have until you do your looping but we need to know how many there are when initializing the array. I would suggest changing from an Array to a List so your collection can be dynamic. Something like this:

int factorNumber = 1;
List<Integer> factors = new ArrayList<>();
while(factorNumber <= number){
    if(number % factorNumber == 0){
        factors.add(factorNumber);
    }
    factorNumber++;
}

The final product of this, though, is a List<Integer. If you want to return an Array, you are going to have to loop through and make an array:

int[] output = new int[factors.size()];
for (int i=0; i<factors.size(); i++){
    output[i] = factors.get(i);
}
return output;

Or if you don't like my changes and you don't want to use List at all you can do something like this to solve your problem:

int factorNumber = 1;
int varArrayStoreID = 0;
int[] factors = new int[number];
while(factorNumber <= number){
    if(number % factorNumber == 0){
        varArrayStoreID = varArrayStoreID + 1;
        factors[varArrayStoreID] = factorNumber;
    }
    factorNumber++;
}
return Arrays.copyOfRange(factors, 0, varArrayStoreID);
gonzo
  • 2,103
  • 1
  • 15
  • 27