2019-03-21 11:52:35 +05:30
---
id: 5a23c84252665b21eecc7ee0
title: Left factorials
challengeType: 5
2019-08-05 09:17:33 -07:00
forumTopicId: 302302
2021-01-13 03:31:00 +01:00
dashedName: left-factorials
2019-03-21 11:52:35 +05:30
---
2020-11-27 19:02:05 +01:00
# --description--
**Left factorials**, $ !n $, may refer to either *subfactorials* or to *factorial sums* . The same notation can be confusingly seen used for the two different definitions. Sometimes, *subfactorials* (also known as *derangements* ) may use any of the notations:
2020-03-30 11:23:18 -05:00
2019-03-21 11:52:35 +05:30
< ul >
2019-05-23 13:57:59 +09:00
< li > $!n`$< / li >
< li > $!n$< / li >
< li > $n¡$< / li >
2019-03-21 11:52:35 +05:30
< / ul >
2020-11-27 19:02:05 +01:00
(It may not be visually obvious, but the last example uses an upside-down exclamation mark.) This task will be using this formula for **left factorial** :
$ !n = \\sum\_{k=0}^{n-1} k! $
2019-03-21 11:52:35 +05:30
where $!0 = 0$
2020-11-27 19:02:05 +01:00
# --instructions--
2020-03-30 11:23:18 -05:00
2019-03-21 11:52:35 +05:30
Write a function to calculate the left factorial of a given number.
2020-11-27 19:02:05 +01:00
# --hints--
`leftFactorial` should be a function.
```js
assert(typeof leftFactorial == 'function');
2019-03-21 11:52:35 +05:30
```
2020-11-27 19:02:05 +01:00
`leftFactorial(0)` should return a number.
2019-03-21 11:52:35 +05:30
2020-11-27 19:02:05 +01:00
```js
assert(typeof leftFactorial(0) == 'number');
```
2020-03-30 11:23:18 -05:00
2020-11-27 19:02:05 +01:00
`leftFactorial(0)` should return `0` .
2019-03-21 11:52:35 +05:30
```js
2020-11-27 19:02:05 +01:00
assert.equal(leftFactorial(0), 0);
```
2020-09-15 09:57:40 -07:00
2020-11-27 19:02:05 +01:00
`leftFactorial(1)` should return `1` .
```js
assert.equal(leftFactorial(1), 1);
```
`leftFactorial(2)` should return `2` .
```js
assert.equal(leftFactorial(2), 2);
```
`leftFactorial(3)` should return `4` .
```js
assert.equal(leftFactorial(3), 4);
2019-03-21 11:52:35 +05:30
```
2020-11-27 19:02:05 +01:00
`leftFactorial(10)` should return `409114` .
2019-03-21 11:52:35 +05:30
2020-11-27 19:02:05 +01:00
```js
assert.equal(leftFactorial(10), 409114);
```
2020-03-30 11:23:18 -05:00
2020-11-27 19:02:05 +01:00
`leftFactorial(17)` should return `22324392524314` .
```js
assert.equal(leftFactorial(17), 22324392524314);
```
`leftFactorial(19)` should return `6780385526348314` .
```js
assert.equal(leftFactorial(19), 6780385526348314);
```
# --seed--
## --seed-contents--
```js
function leftFactorial(n) {
}
```
# --solutions--
2019-03-21 11:52:35 +05:30
```js
function leftFactorial(n) {
2020-03-30 11:23:18 -05:00
if (n == 0) return 0;
if (n == 1) return 1;
// Note: for n>=20, the result may not be correct.
// This is because JavaScript uses 53 bit integers and
// for n>=20 result becomes too large.
let res = 2,
fact = 2;
for (var i = 2; i < n ; i + + ) {
res += fact;
fact *= i + 1;
}
return res;
2019-03-21 11:52:35 +05:30
}
```