Trang chủ / Javascript / Tìm ước chung lớn nhất của nhiều số

Tìm ước chung lớn nhất của nhiều số

Mã nguồn:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>GCD (greatest common divisor) of more than 2 integers</title>
<script>
function gcd_more_than_two_numbers(input) {
  if (toString.call(input) !== "[object Array]")  
        return  false;  
  var len, a, b;
	len = input.length;
	if ( !len ) {
		return null;
	}
	a = input[ 0 ];
	for ( var i = 1; i < len; i++ ) {
		b = input[ i ];
		a = gcd_two_numbers( a, b );
	}
	return a;
}

function gcd_two_numbers(x, y) {
  if ((typeof x !== 'number') || (typeof y !== 'number')) 
    return false;
  x = Math.abs(x);
  y = Math.abs(y);
  while(y) {
    var t = y;
    y = x % y;
    x = t;
  }
  return x;
}
 document.write(gcd_more_than_two_numbers([3,15,27])+"<br/>");
 document.write(gcd_more_than_two_numbers([5,10,15,25])+"<br/>");
</script>

</head>
<body>
</body>
</html>

Xem ví dụ

 

Lưu đồ thuật toán:

Flowchart: JavaScript Math- GCD (greatest common divisor) of more than 2 integers

Thấy bài viết hữu ích?

Ủng hộ tác giả để có thêm nhiều bài viết chất lượng nhé!

Tư vấn lộ trình CNTT 🤖