diff --git a/curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-65-convergents-of-e.md b/curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-65-convergents-of-e.md index ca61b8fa36..7a1383a7f0 100644 --- a/curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-65-convergents-of-e.md +++ b/curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-65-convergents-of-e.md @@ -26,20 +26,44 @@ $2, 3, \\dfrac{8}{3}, \\dfrac{11}{4}, \\dfrac{19}{7}, \\dfrac{87}{32}, \\dfrac{1 The sum of digits in the numerator of the 10th convergent is $1 + 4 + 5 + 7 = 17$. -Find the sum of digits in the numerator of the 100th convergent of the continued fraction for `e`. +Find the sum of digits in the numerator of the `n`th convergent of the continued fraction for `e`. # --hints-- -`convergentsOfE()` should return a number. +`convergentsOfE(10)` should return a number. ```js -assert(typeof convergentsOfE() === 'number'); +assert(typeof convergentsOfE(10) === 'number'); ``` -`convergentsOfE()` should return 272. +`convergentsOfE(10)` should return `17`. ```js -assert.strictEqual(convergentsOfE(), 272); +assert.strictEqual(convergentsOfE(10), 17); +``` + +`convergentsOfE(30)` should return `53`. + +```js +assert.strictEqual(convergentsOfE(30), 53); +``` + +`convergentsOfE(50)` should return `91`. + +```js +assert.strictEqual(convergentsOfE(50), 91); +``` + +`convergentsOfE(70)` should return `169`. + +```js +assert.strictEqual(convergentsOfE(70), 169); +``` + +`convergentsOfE(100)` should return `272`. + +```js +assert.strictEqual(convergentsOfE(100), 272); ``` # --seed-- @@ -47,16 +71,47 @@ assert.strictEqual(convergentsOfE(), 272); ## --seed-contents-- ```js -function convergentsOfE() { +function convergentsOfE(n) { return true; } -convergentsOfE(); +convergentsOfE(10); ``` # --solutions-- ```js -// solution required +function convergentsOfE(n) { + function sumDigits(num) { + let sum = 0n; + while (num > 0) { + sum += num % 10n; + num = num / 10n; + } + return parseInt(sum); + } + + // BigInt is needed for high convergents + let convergents = [ + [2n, 1n], + [3n, 1n] + ]; + const multipliers = [1n, 1n, 2n]; + for (let i = 2; i < n; i++) { + const [secondLastConvergent, lastConvergent] = convergents; + const [secondLastNumerator, secondLastDenominator] = secondLastConvergent; + const [lastNumerator, lastDenominator] = lastConvergent; + const curMultiplier = multipliers[i % 3]; + + const numerator = secondLastNumerator + curMultiplier * lastNumerator; + const denominator = secondLastDenominator + curMultiplier * lastDenominator; + + convergents = [lastConvergent, [numerator, denominator]] + if (i % 3 === 2) { + multipliers[2] += 2n; + } + } + return sumDigits(convergents[1][0]); +} ```