-
Description Be careful! You were previously implicitly defining a global
fact
when you really should not have done that. A lot of these problems can be solved by including that"use strict";
at the start of a function, which is especially important when you're starting out. Also, factorial of 0 is 1, and factorial of negatives is undefined. It's also nice to have proper indentation to make programs a little easier to read.Code function factorial (n) { "use strict"; if (n < 0) { return NaN } let i, fact i = fact = 1 while (i <= n) { fact *= i i++ } return fact }
Test Cases const chai = require("chai"); const assert = chai.assert; describe("Solution", function() { it("should test for something", function() { assert(factorial(0), 1); assert(factorial(1), 1); assert(factorial(5), 120); assert(factorial(8),40320); assert(factorial(15),1307674368000); }); });
Output:
-
Code - function factorial (n) {
if (n <= 0) return 0let i = fact = 1- "use strict";
- if (n < 0) {
- return NaN
- }
- let i, fact
- i = fact = 1
- while (i <= n) {
fact *= ii++- fact *= i
- i++
- }
- return fact
- }
Test Cases - const chai = require("chai");
- const assert = chai.assert;
- describe("Solution", function() {
- it("should test for something", function() {
- assert(factorial(0), 1);
- assert(factorial(1), 1);
- assert(factorial(5), 120);
- assert(factorial(8),40320);
- assert(factorial(15),1307674368000);
- });
- });
- All
- {{group.name}} ({{group.count}})
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}