user6752436
user6752436

Reputation:

Find common Factor of two values

I have the following javascript code to calculate the factors of numbers.

var some = [];
var main = "";
var final = "";

function text(data) {
  spliter = data.split(",");

  var k = 0;
  while (k < spliter.length) {
    var meethi = 0;;
    main = spliter[k];

    var datas = "";
    for (var i = 1; i <= 10; i += 1) {
      meethi = Math.abs(main / i);
      datas = meethi;
      some.push('' + datas + '');
    }
    some.forEach(myFunction);
    final += res + '<br>';
    k++;
  }

  return final;
}
var max = 0;
var res = "";

function myFunction(item) {
  var van = item.split(".");
  if (van[1] == undefined) {
    var high = Math.floor(main / van[0]);
    if (high > max) {
      max = high;
      res += max + ':';
    }
  }
}
document.getElementById('demo').innerHTML = text('124,20');
<p id="demo"></p>

My program gets the factors with two values. How do I identify the common factor of both values,only the highest common value?

example like ('124,20') output --> 4

I tried the code with my own knowledge. If you have any other suggestion for code please tell me and correct my code with my desired result.

my fiddle

Upvotes: 5

Views: 3193

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You could use for the greatest common divisor Euclid's algorithm.

function gcd(k, n) {
    return k ? gcd(n % k, k) : n;
}

console.log(gcd(124, 20));
console.log([10, 500, 600].reduce(gcd));

Upvotes: 9

Related Questions