我必须确定数组中的数字是否是给定数字的因子。

huangapple go评论69阅读模式
英文:

I have to figure out if the numbers in an array are factors of a given number

问题

public static boolean areFactors(int[] arrNum, int n){

   if (arrNum == null || arrNum.length == 0){
     return false;
   }

   for (int i = 0; i < arrNum.length; i++){
     if (n % arrNum[i] == 0){
       return true;
     }
   }
   return false;
 }
英文:

Ex:

  • areFactors( [3,4,6], 12 ) --> true
  • areFactors( [2,4,6], 10 ) --> false
  • areFactors( [], 6 ) --> false
public static boolean areFactors(int[] arrNum, int n){

   if (arrNum == null || arrNum.length == 0){
     return false;
   }

   for (int i = 0; i &lt; arrNum.length; i++){
     if (n % arrNum[i] == 0){
       return true;
     }
   }
   return false;
 }

There are a few tests that won't pass and I also get division by zero exception.

答案1

得分: 2

如果数组中包含任何0,则应返回false。
除此之外,在遇到不是n的因子的数字时,应返回false
仅在循环之后返回true(即在验证所有数组元素都是n的因子后返回)。

public static boolean areFactors(int[] arrNum, int n) {
    
   if (arrNum == null || arrNum.length == 0) {
     return false;
   }

   for (int i = 0; i < arrNum.length; i++) {
     if (arrNum[i] == 0 || n % arrNum[i] != 0) {
       return false;
     }
   }
   return true;
}
英文:

If the array contains any 0s, you should return false.

Other than that, you should return false when you encounter a number that is not a factor of n.

Return true only after the loop (i.e. after validating that all the array elements are factors of n).

public static boolean areFactors (int[] arrNum, int n) {

   if (arrNum == null || arrNum.length == 0) {
     return false;
   }

   for (int i = 0; i &lt; arrNum.length; i++) {
     if (arrNum[i] == 0 || n % arrNum[i] != 0) {
       return false;
     }
   }
   return true;
}

答案2

得分: 0

你的代码中存在一个逻辑错误。

在这里,你可以找到一个解决方案,以实现你想要的功能:

public static boolean areFactors(int[] arrNum, int n) {
    if (arrNum == null || arrNum.length == 0) {
        return false;
    }

    for (int i = 0; i < arrNum.length; i++) {
        int num = arrNum[i];
        if (num != 0 && n % num != 0) {
            return false;
        }
    }
    return true;
}
英文:

There is a logical error in your code.

Here you can find a solution what you are going to achieve:

public static boolean areFactors(int[] arrNum, int n) {
    if (arrNum == null || arrNum.length == 0) {
        return false;
    }

    for (int i = 0; i &lt; arrNum.length; i++) {
        int num = arrNum[i];
        if (num != 0 &amp;&amp; n % num != 0) {
            return false;
        }
    }
    return true;
}

huangapple
  • 本文由 发表于 2020年10月12日 16:57:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64314650.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定