Skip to content

Commit 9ed39f3

Browse files
committed
Added factorial method to API
1 parent 2acfe58 commit 9ed39f3

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,7 @@ FUNCTION| DESCRIPTION
257257
<nobr>`set(key,value)`</nobr> | Set option. Currently supports the following keys: `observer` (1=quantum, 2=classic), `maxcliquesperloc` (number) and `maxstatesperclique` (number).
258258
<nobr>`get(key)`</nobr> | Get option value.
259259
<nobr>`clone(x)`</nobr> | Makes a deep copy of the given data structure.
260+
<nobr>`factorial(x)`</nobr> | Factorial of `x`.
260261
<nobr>`shuffle(arr)`</nobr> | Shuffles an array in place using the Fisher-Yates shuffle.
261262
<nobr>`*comb(arr,[size])`</nobr> | Generates all combinations of a set. `size` is the length of the combination. An example:<br/>`comb([a,b,c],2)` -> `[a,b] [a,c] [b,c]`
262263
<nobr>`*perm(arr,[size])`</nobr> | Generates all permutations of a set. `size` is the length of the permutation. An example:<br/>`perm([a,b,c],2)` -> `[a,b] [a,c] [b,a] [b,c] [c,a] [c,b]`

lib/ModelAPI.js

+13
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ class ModelAPI {
1414
constructor() {
1515
this._id = 0;
1616
this._opt = {};
17+
this._fmem = [BigInt(0), BigInt(1)]; // Factorial memoization
1718
}
1819

1920
/**
@@ -51,6 +52,18 @@ class ModelAPI {
5152
return JSON.parse(JSON.stringify(o));
5253
}
5354

55+
/**
56+
* Factorial with BigInt and memoization.
57+
* @param {bigint} n
58+
* @return {bigint} n!
59+
*/
60+
factorial(n) {
61+
while( this._fmem.length <= n ) {
62+
this._fmem.push( this._fmem[ this._fmem.length-1 ] * BigInt( this._fmem.length ) );
63+
}
64+
return BigInt( this._fmem[n] );
65+
}
66+
5467
/**
5568
* Generates all combinations of a set.
5669
* comb([a,b,c],2) -> [a,b] [a,c] [b,c]

server/api.mjs

+13
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ class ModelAPI {
1414
constructor() {
1515
this._id = 0;
1616
this._opt = {};
17+
this._fmem = [BigInt(0), BigInt(1)]; // Factorial memoization
1718
}
1819

1920
/**
@@ -51,6 +52,18 @@ class ModelAPI {
5152
return JSON.parse(JSON.stringify(o));
5253
}
5354

55+
/**
56+
* Factorial with BigInt and memoization.
57+
* @param {bigint} n
58+
* @return {bigint} n!
59+
*/
60+
factorial(n) {
61+
while( this._fmem.length <= n ) {
62+
this._fmem.push( this._fmem[ this._fmem.length-1 ] * BigInt( this._fmem.length ) );
63+
}
64+
return BigInt( this._fmem[n] );
65+
}
66+
5467
/**
5568
* Generates all combinations of a set.
5669
* comb([a,b,c],2) -> [a,b] [a,c] [b,c]

0 commit comments

Comments
 (0)