Javascript - Tính tổ hợp của n và r
Tính tổ hợp của n và r
Viết một hàm JavaScript để tính toán kết hợp của n và r.
Công thức là: n! / (R! * (N - r)!).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript function to calculate the combination of n and r. The formula is : n!/(r!*(n - r)!)</title>
<script>
function product_Range(a,b) {
var prd = a,i = a;
while (i++< b) {
prd*=i;
}
return prd;
}
function combinations(n, r)
{
if (n==r)
{
return 1;
}
else
{
r=(r < n-r) ? n-r : r;
return product_Range(r+1, n)/product_Range(1,n-r);
}
}
document.write(combinations(6, 2)+"<br/>");
document.write(combinations(5, 3)+"<br/>");
</script>
</head>
<body>
</body>
</html>
Lưu đồ thuật toán: