简体   繁体   English

查找两个值的公因子

[英]Find common Factor of two values

I have the following javascript code to calculate the factors of numbers. 我有以下javascript代码来计算数字因子。

 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 例如('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 我的小提琴

You could use for the greatest common divisor Euclid's algorithm . 您可以使用最大公因数Euclid算法

 function gcd(k, n) { return k ? gcd(n % k, k) : n; } console.log(gcd(124, 20)); console.log([10, 500, 600].reduce(gcd)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM