diff --git a/challenges/euler/readme.md b/challenges/euler/readme.md index ac21586..882365b 100644 --- a/challenges/euler/readme.md +++ b/challenges/euler/readme.md @@ -36,7 +36,7 @@ The source code can be found in the [src](src) directory. My thoughts about some - [x] [22 - Names scores](src/22%20-%20Names%20scores.ts) - [ ] 23 - Non-abundant sums - [ ] 24 - Lexicographic permutations -- [ ] 25 - 1000-digit Fibonacci number +- [x] [25 - 1000-digit Fibonacci number](src/25%20-%201000-digit%20Fibonacci%20number.ts) - [ ] 26 - Reciprocal cycles - [ ] 27 - Quadratic primes - [ ] 28 - Number spiral diagonals diff --git a/challenges/euler/src/25 - 1000-digit Fibonacci number.ts b/challenges/euler/src/25 - 1000-digit Fibonacci number.ts new file mode 100644 index 0000000..91dce8c --- /dev/null +++ b/challenges/euler/src/25 - 1000-digit Fibonacci number.ts @@ -0,0 +1,43 @@ +// The Fibonacci sequence is defined by the recurrence relation: +// Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. +// The 12th term, F12, is the first term to contain three digits. +// What is the index of the first term in the Fibonacci sequence to contain 1000 digits? +export = {}; + +function* fibonacciSequence(): Generator { + let current = BigInt(1); + let a = BigInt(1); + let b = BigInt(1); + + yield BigInt(1); + + while (true) { + current = b; + yield current; + + b = a + b; + a = current; + } +} + +const firstTermWithXDigits = (sequence: Generator, digitCount: number) => { + let { value: term } = sequence.next(); + let index = 1; + + while (term.toString().length !== digitCount) { + term = sequence.next().value; + index += 1; + } + + return { + value: term, + index + }; +}; + +// Output + +const fibonacci = fibonacciSequence(); +const firstTerm = firstTermWithXDigits(fibonacci, 1000); + +console.log(firstTerm);