Home > Back-end >  Return the sum of all items of the array that are factors of n
Return the sum of all items of the array that are factors of n

Time:03-16

I am tasked with returning the sum of all the factors of n within the given array. I wrote a test and it is expecting 10 to be returned however I am getting 0 returned. Any tips on why this may be the case? Currently, the code I have written so far is below. The first if statement is there to ensure that if the array is null it just returns 0.

    public static int sumFactors(int[] data, int n) {
    if (data == null || data.length == 0) {
           return 0;
        
    } int sum = 0;
     
        for (int i = 0; i < data.length; i  )
        {
            if (data[i] % n == 0)
            {
                sum = sum   data[i];
            }
        }
     
        return sum;
    }

CodePudding user response:

You got it the other way around, x % n gives the remainder of x divided by n, so the condition to check if data[i] divides n is n % data[i] == 0

CodePudding user response:

public static int sumFactors(int[] data, int n) {
if (data == null || data.length == 0) {
    return 0;    
} 
int sum = 0;
for (int i = 0; i < data.length; i  ){
    if (n % data[i]  == 0)
    {
        sum = sum   data[i];
    }
}
 
return sum;
}
  • Related