• 求公约数和比值


    <!doctype html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>公约数  简比</title>
    	<style>
    		div{padding:20px;}
    	</style>
    </head>
    <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>
    

      

  • 相关阅读:
    LeetCode
    <OFFER15> 15_NumberOf1InBinary
    《OFFER14》14_CuttingRope
    Convert DataFrame string complex i to j python // “Cloning” row or column vectors
    Sorting arrays in NumPy by column
    【説明する】深度优先及宽度优先算法比较
    codevs 2924 数独挑战 x(三种做法+超详细注释~)
    第四次考试大整理
    洛谷 P1048 采药
    codevs 3137-3139 栈练习 x
  • 原文地址:https://www.cnblogs.com/youzhuxiaoyao/p/8658074.html
Copyright © 2020-2023  润新知