Javascript - Tính giai thừa giảm của một số

Tính giai thừa giảm của một số

Viết một hàm JavaScript để tính giai thừa giảm của một số.

Cho x là một số thực (nhưng thường là số nguyên).
Gọi k là số nguyên dương.
Khi đó x để (lũy thừa của) k giảm là:

kth falling factorial power of x

Đây được gọi là lũy thừa giảm thứ k của x.

Mã nguồn:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript function to calculate the falling factorial of a number</title>
   <script>
     function fallingFactorial(n, k) 
{
  var i = (n - k + 1),
    r = 1;
  if (n < 0) 
  {
    throw new Error("n must be positive.");
  }
  if (k > n)
  {
    throw new Error("k cannot be greater than n.");
  }
  while (i <= n) 
  {
    r *= i++;
  }
  return r;
}
document.write(fallingFactorial(10, 2));
   </script>
</head>
<body>

</body>
</html>

Xem ví dụ

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

Flowchart: JavaScript Math - calculate the falling factorial of a number