![](/img/trans.png)
[英]Given a number n, return true is all the factors of n are prime numbers. Note that 1 and the number itself are not considered as factors
[英]Return the sum of all items of the array that are factors of n
我的任務是返回給定數組中 n 的所有因子的總和。 我寫了一個測試,它期望返回 10,但是我得到 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;
}
反過來, 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.