user5380448
user5380448

Reputation:

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!

Upvotes: 0

Views: 525

Answers (2)

Jonathan
Jonathan

Reputation: 1402

Here's one way you could do it that supports multiple numbers:

function find_common_factors(...args) {
  let common_factors = [1];
  let min_val = Math.min(...args)
  for (let fx = 2; fx <= min_val; fx++)
    if (args.every(arg => arg / fx % 1 === 0))
      common_factors.push(fx)
  return common_factors;
}

console.log(find_common_factors(10, 15)) // [1, 5]
console.log(find_common_factors(18, 36, 90)) // [1, 2, 3, 6, 9, 18]

Upvotes: 1

mamazu
mamazu

Reputation: 47

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.

Upvotes: 1

Related Questions