This commit is contained in:
2025-02-03 14:28:54 +01:00
parent 03bdd63342
commit 3ffb7f8181
3 changed files with 71 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
Consider the following numbers (where n! is factorial(n)):
u1 = (1 / 1!) * (1!)
u2 = (1 / 2!) * (1! + 2!)
u3 = (1 / 3!) * (1! + 2! + 3!)
...
un = (1 / n!) * (1! + 2! + 3! + ... + n!)
Which will win: 1 / n! or (1! + 2! + 3! + ... + n!)?
Are these numbers going to 0 because of 1/n! or to infinity due to the sum of factorials or to another number?
Task
Calculate (1 / n!) * (1! + 2! + 3! + ... + n!) for a given n, where n is an integer greater or equal to 1.
Your result should be within 10^-6 of the expected one.
Remark
Keep in mind that factorials grow rather rapidly, and you need to handle large inputs.
Hint
You could try to simplify the expression.

View File

@@ -0,0 +1,36 @@
export function factorial(n: number): number {
let result = n;
for (let i = n - 1; i > 0; i--) {
result *= i;
}
return result;
}
// inclusive both sides
export function partialFactorial(to: number, from: number): number {
if (to === from) return 1;
if (to > from) {
throw new Error('to must be less than from');
}
let result = from;
for (let i = from - 1; i >= to; i--) {
result *= i;
}
return result;
}
export function going(n: number): number {
// your code
let result = 1 / n;
for (let i = 2; i <= n; i++) {
result += 1 / partialFactorial(i, n);
}
return result;
}

View File

@@ -0,0 +1,14 @@
import {going} from './solution'
import {assert} from "chai";
function testing(n:number, expected:number) {
assert.approximately(going(n), expected, 1e-6)
}
describe("Fixed Tests going", function() {
it("Basic tests", function() {
testing(5, 1.275);
testing(6, 1.2125);
testing(7, 1.173214);
});
});