Determining if an array is a factor chain

Viewed 675

I would love to know why this code is failing some tests. It is intentionally not using any ES6 code.

Here is the prompt:

*A factor chain is an array where each previous element is a factor of the next consecutive element. The following is a factor chain:

[3, 6, 12, 36]
// 3 is a factor of 6
// 6 is a factor of 12
// 12 is a factor of 36

Create a function that determines whether or not an array is a factor chain.*

My code:

function factorChain(arr) {
    var isChain = true;
  
  for (var i = 0; i < arr.length; i++) {
    if ((arr[i + 1] / arr[i]) !== Math.floor(arr[i + 1] / arr[i])) {
      isChain = false;            
    }
  }

  return isChain;
}
1 Answers

You should loop up to arr.length - 1 as you are accessing the element at the current index and the one at the next index on each iteration. Using the remainder operator to check if a number is a factor of another can enhance code clarity. Furthermore, there is no need to assign the result to a variable; simply returning false the first time the condition does not match will exit the function.

function factorChain(arr) { 
  for (var i = 0; i < arr.length - 1; i++) {
    if (arr[i+1] % arr[i] != 0) {
      return false;            
    }
  }
  return true;
}
Related