最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Test whether all array elements are factors of a number - return inside a for loop - Stack Overflow

programmeradmin7浏览0评论

I have the following question:

Write a function that returns true if all integers in an array are factors of a number, and false otherwise.

I tried the code below:

function checkFactors(factors, num) {

  for (let i=0; i<factors.length; i++){
    let element = factors[i];
      console.log(element)

    if (num % element !== 0){
      return false 
    }
    else {
      return true
    }
  }
}

console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false

I have the following question:

Write a function that returns true if all integers in an array are factors of a number, and false otherwise.

I tried the code below:

function checkFactors(factors, num) {

  for (let i=0; i<factors.length; i++){
    let element = factors[i];
      console.log(element)

    if (num % element !== 0){
      return false 
    }
    else {
      return true
    }
  }
}

console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false

My solution returns true which is wrong. I know it's the else statement that's messing it up. But I want to understand why the else statement can't go there.

Share Improve this question edited Jul 21, 2019 at 11:37 Jonas Wilms 138k20 gold badges157 silver badges160 bronze badges asked Apr 6, 2019 at 13:04 PineNuts0PineNuts0 5,23423 gold badges73 silver badges128 bronze badges 5
  • 2 You should get the return true out of the loop ;) and leave the return false inside the loop :) The reason for it is that otherwise your loop really stops after the first checking, returning either true or false, and you want it to return false as soon as something is not a factor. The return true outside of the loop would then indicate that all numbers supplied where factors of the number argument – Icepickle Commented Apr 6, 2019 at 13:07
  • 2 FYI, it's not just you, this is one of the most mon errors people make when they first start out with programming and loops. :-) – T.J. Crowder Commented Apr 6, 2019 at 13:09
  • 1 @t.j.crowder yet we don't have a good dupetarget for it. – Jonas Wilms Commented Apr 6, 2019 at 13:14
  • 2 @JonasWilms - Yeah, I bookmarked this one on the basis that there isn't a lot of extraneous stuff, it really is just the earlier return thing. :-) – T.J. Crowder Commented Apr 6, 2019 at 13:18
  • @T.J.Crowder stackoverflow./questions/42913798/… is the general dupe I wrote for this class of problems. – Barmar Commented Apr 6, 2019 at 18:43
Add a ment  | 

7 Answers 7

Reset to default 7

You are working in a chocolate store, and your boss tells you to check wether all chocolates (there are chili chocolate, caramel chocolate and coffee chocolate) are delicious. He tells you the following:

Go through all chocolates, and for each chocolate, taste it, if it is fine, tell me that everything is fine, otherwise tell me that something is wrong¹

You start with the first chocolate, which is chili chocolate, it tastes delucious, you go to your boss and tell him that everything is fine. Your boss yells at you because you haven't tasted the caramel chocolate and the coffee chocolate yet.

You realize that your boss actually wanted you to do:

Go through the chocolates, for each chocolate, taste it, if it doesnt taste well tell, tell me immeadiately, otherwise continue until you tasted them all, then return to me and tell me that everything is fine.²

Or in code:

 // ¹
  function checkChocolates(chocolates) {
    for(const chocolate of chocolates) {
       if(isTasty(chocolate)) {
         return true;
       } else {
         return false;
       }
    }
 }

 // ²
 function checkChocolates(chocolates) {
   for(const chocolate of chocolates) {
     if(isTasty(chocolate)) {
       continue; // this could be omitted, as a loop keeps looping nevertheless
     } else {
       return false;
     }
   }
   return true;
 }

As this is a very mon task in programming, there is already a shorter way to express this:

 if(chocolates.every(isTasty)) {
   alert("all chocolates are fine");
 } else {
    alert("Oh, that doesnt taste good");
 }

whereas isTasty is a function taking a chocolate and returning either true or false.


If you didn't grasp it yet, just try it out! Buy some chocolate, and taste it! If someone tells you "eating choclate isn't learning", respond with "I'm doing rubber duck debugging" and no one can plain :)

Just place return true out of for loop,

If you keep return true in else part as soon as any of value which does not satisfies num % element !== 0 your code will return true which should not happen in this case as you're checking for all the values in array should be factor of given number

Let's understand by 1st example

  • On first element in array 1 it will check if condition num % element !== 0 which turns out false, so it will go to else condition and return true from function and will not check for rest of values.
  • So you need to keep return true at the end so if any of the value in loop doesn't satisfy the if condition than only control will go to return true

function checkFactors(factors, num) {

  for (let i=0; i<factors.length; i++){
    let element = factors[i];
    if (num % element !== 0){
      return false 
    }
  }
  return true
}



console.log(checkFactors([1, 2, 3, 8], 12)) //➞ false
console.log(checkFactors([1, 2], 2))

In short - In such case where you want all of them must match a condition as a thumb rule you can consider it like

  1. keep the failing case return value inside for loop
  2. keep the passing case return value at the end of function

JS have a inbuilt method Array.every for such cases

function checkFactors(factors, num) {
   return factors.every(element => num % element === 0);
}
console.log(checkFactors([1, 2, 3, 8], 12)); 
console.log(checkFactors([1, 2], 2));

Inside the loop the input num was was tested for divisibility, if the num was divisible the control was going in the else block from where the function returned true.

The loop was not checking for all numbers of the input array it was returning true when the first number was divisible.

Just use a flag variable to see if all of the elements are divisible by the input number num, if any one is not divisible the flag will set to false and then we can break out of the loop and return it as there is no point to check the other numbers.

function checkFactors(factors, num) {
  let flag = true;
  for (let i=0; i<factors.length; i++){
    let element = factors[i];
    if (num % element !== 0){
      flag = false;
      break;
    }
  }
  return flag;
}

console.log(checkFactors([1, 2, 3, 8], 12)); 
console.log(checkFactors([1, 2], 2));
console.log(checkFactors([2, 4, 3, 6, 9], 12));
console.log(checkFactors([3, 5, 2, 6, 9], 15));
console.log(checkFactors([4, 2, 8, 1], 16));

You can also use Array.every to check the same in a concise way:

function checkFactors(factors, num) {
   return factors.every(element => num % element === 0);
}
console.log(checkFactors([1, 2, 3, 8], 12)); 
console.log(checkFactors([1, 2], 2));
console.log(checkFactors([2, 4, 3, 6, 9], 12));
console.log(checkFactors([3, 5, 2, 6, 9], 15));
console.log(checkFactors([4, 2, 8, 1], 16));

Yes, "else" causing the issue. I removed it and added "return true" outside of for loop.

function checkFactors(factors, num) {

  for (let i=0; i<factors.length; i++){
    let element = factors[i];
      console.log(element)

    if (num % element !== 0){
      return false 
    }
  }
  return true;
}

Your code's logic is wrong. You should check all the array's Elements, if all elements satisfy the condition, return true, but if one of them not satisfy the condition, return false immediately. The else means one item satisfy the condition, but not all elements. That's where the problem is.

const checkFactors = (factors, num) => factors.reduce((acc, x)=>acc && num%x===0);

or

const checkFactors = (factors, num) => factors.every(x => num%x===0);
            package Map;
            import java.util.ArrayList;
            import java.util.Scanner;

            public class Question3 {
                public void factorize(int number) {
                    ArrayList<Integer> temp = new ArrayList<>();
                    for (int i = 1; i <= number; i++) {
                        if (number % i == 0) {
                            temp.add(i);
                        }
                    }
                }

                public static void main(String[] args) {
                    Scanner sc = new Scanner(System.in);
                    System.out.println("Enter the number do you want to check factorize: ");
                    int i = sc.nextInt();
                    Question3 question3 = new Question3();
                    question3.factorize(i);

                }
            }
发布评论

评论列表(0)

  1. 暂无评论