# 求公约数和比值

<!doctype html>
<html lang="en">
<meta charset="UTF-8">
<title>公约数  简比</title>
<style>
</style>
<body>

<script type="text/javascript">
//求两个数的比值
function getRatio(a, b){
var ma = 1,mb = 1,c;//倍数
a += '',b += '';
if(a.indexOf('.')>-1){
ma = Math.pow(10,a.split('.')[1].length);
}else if(a.indexOf('/')>-1){
ma = +a.split('/')[1]
}
if(b.indexOf('.')>-1){
mb = Math.pow(10,b.split('.')[1].length);
}else if(b.indexOf('/')>-1){
mb = +b.split('/')[1]
}
a = eval(a)*ma*mb;
b = eval(b)*ma*mb;
c =  getCommonDivisor(a,b);
console.log('最小整数比：'+(a/c)+':'+(b/c));
}

// 计算多个数字的最简比值
function getRatioMore(arr){
var i = 0, ln = arr.length, newArr = [],
resArr = [],
mnum=1, multiple = 1, c;
//制作新数组
for(i=0; i<ln; i++){
arr[i] += '';
if(arr[i].indexOf('.')>-1){
mnum = Math.pow(10, arr[i].split('.')[1].length);
multiple *= mnum;
}else if(arr[i].indexOf('/') >-1){
mnum = +arr[i].split('/')[1];
multiple *= mnum;
}
}
for(var j=0; j<ln; j++){
newArr[j] = arr[j] * multiple;
}
console.log(newArr);
c = getCommonDivisorMore(newArr);//求公约数
for(var i=0; i<ln; i++){
resArr.push(newArr[i]/c);
}
console.log(resArr.join(':'));
}
//计算最大公约数,阿基里德算法
function getCommonDivisor(a,b){
var c;
if(a<b){
b = [a,a=b][0];
}
while(c = a%b){
a = b;
b = c;
}
return b;
}
//计算多个数字的最大公约数
function getCommonDivisorMore(arr){
if(arr instanceof Array && arr.length > 1){
var i, ln = arr.length, prevd = arr[0];
for(i = 0; i<ln; i++){
prevd = getCommonDivisor(prevd, arr[i]);
}
return prevd;
}
}
console.log(getCommonDivisorMore([205, 620, 320, 440]));
getRatioMore([20.5, 62, 32, 44])
</script>
</body>
</html>


posted @ 2018-03-27 16:12  幽竹小妖  阅读(366)  评论(0编辑  收藏  举报