feat(euler): challenge 25 - 1000 digit fibonacci index
This commit is contained in:
parent
800791daed
commit
8928aa4335
2 changed files with 44 additions and 1 deletions
|
@ -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
|
||||
|
|
43
challenges/euler/src/25 - 1000-digit Fibonacci number.ts
Normal file
43
challenges/euler/src/25 - 1000-digit Fibonacci number.ts
Normal file
|
@ -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<bigint, bigint, bigint> {
|
||||
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<bigint, bigint, bigint>, 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);
|
Loading…
Reference in a new issue