Write a function in Nodx.js that calculates the factorial of a number.
- User
Write a function in Nodx.js that calculates the factorial of a number.
- Assistant
It looks like there might be a small typo in your request. I'm assuming you meant
Node.js, which is a JavaScript runtime. Here's how you can write a function in JavaScript that calculates the factorial of a number. You can run this function in a Node.js environment:function factorial(n) { if (n < 0) { throw new Error('Factorial is not defined for negative numbers'); } if (n === 0 || n === 1) { return 1; } return n * factorial(n - 1); } // Example usage try { const num = 5; console.log(`Factorial of ${num} is ${factorial(num)}`); } catch (error) { console.error(error.message); }Here's a breakdown of how the code works:
-
Function Declaration: The
factorialfunction is declared and takes a single parametern. -
Base Cases:
- If
nis less than 0, it throws an error because factorials are not defined for negative numbers. - If
nis0or1, it returns1because the factorial of these numbers is1.
- If
-
Recursive Case: If
nis greater than1, the function calls itself withn - 1and multipliesnby the result of this call, effectively calculating the factorial using recursion. -
Example Usage: The function is called with the number
5, and the result is logged to the console.
This code will calculate the factorial of any non-negative integer by using recursion. Feel free to run this in a Node.js environment!
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →