diff --git a/5kyu/going-to-zero-or-to-infinity/description.md b/5kyu/going-to-zero-or-to-infinity/description.md new file mode 100644 index 0000000..57ab64f --- /dev/null +++ b/5kyu/going-to-zero-or-to-infinity/description.md @@ -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. \ No newline at end of file diff --git a/5kyu/going-to-zero-or-to-infinity/solution.ts b/5kyu/going-to-zero-or-to-infinity/solution.ts new file mode 100644 index 0000000..3782fec --- /dev/null +++ b/5kyu/going-to-zero-or-to-infinity/solution.ts @@ -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; +} \ No newline at end of file diff --git a/5kyu/going-to-zero-or-to-infinity/tests.ts b/5kyu/going-to-zero-or-to-infinity/tests.ts new file mode 100644 index 0000000..e4b2e89 --- /dev/null +++ b/5kyu/going-to-zero-or-to-infinity/tests.ts @@ -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); + }); +});