Compare commits

...

5 Commits

Author SHA1 Message Date
trainer2001
eb9ef2da87
Merge e11827b833 into 2c67b48c21 2024-04-25 08:27:11 +08:00
trainer2001
e11827b833 Add factorialBigInt 2021-12-12 17:23:51 +05:30
trainer2001
2b4f12622a Add factorialRecursiveTCOBigInt 2021-12-12 16:59:56 +05:30
trainer2001
9787af0267 Add test for factorialRecursiveTCO 2021-12-12 15:40:21 +05:30
trainer2001
4ea1ad0bb8 Add factorialRecursiveTCO 2021-12-12 15:39:32 +05:30
6 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,12 @@
import factorialBigInt from '../factorialBigInt';
describe('factorialBigInt', () => {
it('should calculate factorial', () => {
expect(factorialBigInt(0n)).toBe(1n);
expect(factorialBigInt(1n)).toBe(1n);
expect(factorialBigInt(5n)).toBe(120n);
expect(factorialBigInt(8n)).toBe(40320n);
expect(factorialBigInt(10n)).toBe(3628800n);
expect(factorialBigInt(100n)).toBe(93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000n);
});
});

View File

@ -0,0 +1,11 @@
import factorialRecursiveTCO from '../factorialRecursiveTCO';
describe('factorialRecursiveTCO', () => {
it('should calculate factorial', () => {
expect(factorialRecursiveTCO(0)).toBe(1);
expect(factorialRecursiveTCO(1)).toBe(1);
expect(factorialRecursiveTCO(5)).toBe(120);
expect(factorialRecursiveTCO(8)).toBe(40320);
expect(factorialRecursiveTCO(10)).toBe(3628800);
});
});

View File

@ -0,0 +1,12 @@
import factorialRecursiveTCOBigInt from '../factorialRecursiveTCOBigInt';
describe('factorialRecursiveTCOBigInt', () => {
it('should calculate factorial', () => {
expect(factorialRecursiveTCOBigInt(0n)).toBe(1n);
expect(factorialRecursiveTCOBigInt(1n)).toBe(1n);
expect(factorialRecursiveTCOBigInt(5n)).toBe(120n);
expect(factorialRecursiveTCOBigInt(8n)).toBe(40320n);
expect(factorialRecursiveTCOBigInt(10n)).toBe(3628800n);
expect(factorialRecursiveTCOBigInt(100n)).toBe(93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000n);
});
});

View File

@ -0,0 +1,13 @@
/**
* @param {bigint} number
* @return {bigint}
*/
export default function factorialBigInt(number) {
let result = 1n;
for (let i = 2n; i <= number; i += 1n) {
result *= i;
}
return result;
}

View File

@ -0,0 +1,12 @@
/**
* @param {number} number
* @return {number}
*/
export default function factorialRecursiveTCO(number) {
function fact(number, accumulator = 1) {
if (number < 2) return accumulator;
else return fact(number - 1, accumulator * number);
}
return fact(number);
}

View File

@ -0,0 +1,12 @@
/**
* @param {bigint} number
* @return {bigint}
*/
export default function factorialRecursiveTCOBigInt(number) {
function fact(number, accumulator = 1n) {
if (number < 2n) return accumulator;
else return fact(number - 1n, accumulator * number);
}
return fact(number);
}