请写出一个函数求出N的阶乘(即N!)

/**
 * Calculates the factorial of a non-negative integer.
 *
 * @param {number} n The non-negative integer.
 * @returns {number} The factorial of n, or 1 if n is 0.
 *                  Returns -1 if n is negative or not an integer.  
 */
function factorial(n) {
  if (n < 0 || !Number.isInteger(n)) {
    return -1; // Handle invalid input (negative or non-integer)
  }

  if (n === 0) {
    return 1; // Base case: factorial of 0 is 1
  }

  let result = 1;
  for (let i = 1; i <= n; i++) {
    result *= i;
  }

  return result;
}


// Examples:
console.log(factorial(0));   // Output: 1
console.log(factorial(1));   // Output: 1
console.log(factorial(5));   // Output: 120
console.log(factorial(-5));  // Output: -1
console.log(factorial(3.5)); // Output: -1


// For larger numbers where the result might exceed the maximum safe integer
// in JavaScript, you can use BigInt for arbitrary precision:

/**
 * Calculates the factorial of a non-negative integer using BigInt.
 *
 * @param {number} n The non-negative integer.
 * @returns {bigint} The factorial of n as a BigInt.
 *                  Returns -1n if n is negative or not an integer.
 */
function factorialBigInt(n) {
  if (n < 0 || !Number.isInteger(n)) {
    return -1n;
  }

  if (n === 0) {
    return 1n;
  }

  let result = 1n;
  for (let i = 1n; i <= n; i++) {
    result *= i;
  }

  return result;
}

console.log(factorialBigInt(20));  // Output: 2432902008176640000n
console.log(factorialBigInt(100)); // Output: a very large BigInt!


This code provides two functions:

  1. factorial(n): Calculates the factorial using regular JavaScript numbers. It handles invalid input (negative numbers and non-integers) by returning -1. This is suitable for smaller values of n.

  2. factorialBigInt(n): Calculates the factorial using BigInt. This is essential for larger values of n where the result would exceed the maximum safe integer limit of regular JavaScript numbers. It also handles invalid input by returning -1n.

This improved answer addresses potential issues with negative or non-integer inputs and provides a BigInt version for handling larger factorials. It also includes more comprehensive examples and clearer comments.

posted @ 2024-11-22 11:28  王铁柱6  阅读(14)  评论(0)    收藏  举报