简体   繁体   English

返回数组中作为 n 的因子的所有项的总和

[英]Return the sum of all items of the array that are factors of n

I am tasked with returning the sum of all the factors of n within the given array.我的任务是返回给定数组中 n 的所有因子的总和。 I wrote a test and it is expecting 10 to be returned however I am getting 0 returned.我写了一个测试,它期望返回 10,但是我得到 0。 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.第一个 if 语句确保如果数组是 null 它只返回 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;
    }

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反过来, x % n给出 x 除以 n 的余数,所以检查 data[i] 是否除以 n 的条件是n % data[i] == 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 (n % data[i]  == 0)
    {
        sum = sum + data[i];
    }
}
 
return sum;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM