Search code examples
javascriptmathfactors

Getting Common Factors From A Set Of Numbers In JavaScript


This question I have has been bothering me for a while now. As the title says, how can I get common factors from a set of numbers? I've made this code but I get the output "Infinity". Have a look:

var x = 10; //Example Numbers
var y = 15;
var fx = 0;

function start() {
  for (fx = 0; fx < x; fx++) {
    if (x / fx % 1 != 0 || y / fx % 1 != 0) { //My attempt at narrowng down whole numbers
      if (x / fx == y / fx) { //Checking if they are the same
        alert(x / fx) //This outputs infinity
      }
    }
  }
}
<!DOCTYPE html>
<html>

<head>
  <title>Eg</title>
</head>

<body>
  <button onclick="start()">Click</button>
</body>

</html>

I think I can see a few errors in there but I'm not 100% sure. Thanks in advance!


Solution

  • What I would recommend you doing is write a function that factors both numbers like so:

    function factorList(number){
      var factors = [];
      for(var i = 1; i < number; i++){
        if(number % i == 0)
          factors.push(i);
      }
      return factors;
    }

    Then in the start() method you just find the factors that are in both lists and there you go:

    function factorList(number) {
      var factors = [];
      for (var i = 1; i <= number; i++) {
        if (number % i == 0)
          factors.push(i);
      }
      return factors;
    }
    var x = 11; //Example Numbers
    var y = 22;
    
    function start() {
      var factors = factorList(x);
      for (var i = factors.length - 1; i >= 0; i--){
        if (y % factors[i] != 0)
          factors.splice(i, 1);
      }
      console.log(factors);
    }
    
    start();

    This solution is easily expandable just filter the factors again if you have more than just two numbers.