freeCodeCamp/curriculum/challenges/english/08-coding-interview-prep/rosetta-code/factorial.english.md

1.6 KiB

title id challengeType
Factorial 597b2b2a2702b44414742771 5

Description

Write a function to return the factorial of a number.

Factorial of a number is given by :

n! = n * (n-1) * (n-2) * ..... * 1

For example : 3! = 3*2*1 = 6 4! = 4*3*2*1 = 24

Note : 0! = 1

Instructions

Tests

tests:
  - text: <code>factorial</code> is a function.
    testString: 'assert(typeof factorial === "function", "<code>factorial</code> is a function.");'
  - text: <code>factorial(2)</code> should return a number.
    testString: 'assert(typeof factorial(2) === "number", "<code>factorial(2)</code> should return a number.");'
  - text: <code>factorial(3)</code> should return 6.")
    testString: 'assert.equal(factorial(3),results[0],"<code>factorial(3)</code> should return 6.");'
  - text: <code>factorial(3)</code> should return 120.")
    testString: 'assert.equal(factorial(5),results[1],"<code>factorial(3)</code> should return 120.");'
  - text: '<code>factorial(3)</code> should return 3,628,800.")'
    testString: 'assert.equal(factorial(10),results[2],"<code>factorial(3)</code> should return 3,628,800.");'

Challenge Seed

function factorial (n) {
  // Good luck!
}

After Test

console.info('after the test');

Solution

function factorial(n) {
  let sum = 1;
  while (n > 1) {
    sum *= n;
    n--;
  }
  return sum;
}