Skip to content

Commit e567797

Browse files
merge: added Problem 25 to Euler (TheAlgorithms#793)
* added Problem 25 * fixed alert * fixed alert * rewrote to improve runtime * Update Problem025.js * fixed typo * added test file for Project-Euler/Problem025.js * Update Project-Euler/test/Problem025.test.js Co-authored-by: Rak Laptudirm <raklaptudirm@gmail.com> * Update Problem025.test.js Co-authored-by: Rak Laptudirm <raklaptudirm@gmail.com>
1 parent 1df1cce commit e567797

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

Project-Euler/Problem025.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Problem 25 - 1000-digit Fibonacci number
3+
*
4+
* @see {@link https://projecteuler.net/problem=25}
5+
*
6+
* The Fibonacci sequence is defined by the recurrence relation:
7+
*
8+
* Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
9+
*
10+
* Hence the first 12 terms will be:
11+
*
12+
* F1 = 1
13+
* F2 = 1
14+
* F3 = 2
15+
* F4 = 3
16+
* F5 = 5
17+
* F6 = 8
18+
* F7 = 13
19+
* F8 = 21
20+
* F9 = 34
21+
* F10 = 55
22+
* F11 = 89
23+
* F12 = 144
24+
* The 12th term, F12, is the first term to contain three digits.
25+
26+
* What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
27+
*/
28+
29+
// brute force method
30+
31+
function fibonacciIndex(t = 1000) {
32+
let digits = 10n**BigInt(t-1),
33+
fib0 = BigInt(0),
34+
fib1 = BigInt(1),
35+
index = 1
36+
while (fib1 < digits) { // using this to compare number of digits instead of .toString() significantly improved run time
37+
const tempfib = fib1
38+
fib1 = fib1 + fib0
39+
fib0 = tempfib
40+
index += 1
41+
}
42+
return(index)
43+
}
44+
45+
export { fibonacciIndex }

Project-Euler/test/Problem025.test.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { fibonacciIndex } from '../Problem025'
2+
3+
describe ('Check Problem 25 - 1000 digit Fibonnaci number', () => {
4+
it('First term of the Fibonnaci sequence containing 3 digits', () => {
5+
expect(fibonacciIndex(3)).toBe(12)
6+
})
7+
8+
it('First term of the Fibonnaci sequence containing 10 digits', () => {
9+
expect(fibonacciIndex(10)).toBe(45)
10+
})
11+
12+
it('First term of the Fibonnaci sequence containing 50 digits', () => {
13+
expect(fibonacciIndex(50)).toBe(237)
14+
})
15+
16+
it('First term of the Fibonnaci sequence containing 100 digits', () => {
17+
expect(fibonacciIndex(100)).toBe(476)
18+
})
19+
20+
it('First term of the Fibonnaci sequence containing 1000 digits', () => {
21+
expect(fibonacciIndex(1000)).toBe(4782)
22+
})
23+
24+
it('First term of the Fibonnaci sequence containing 10000 digits', () => {
25+
expect(fibonacciIndex(10000)).toBe(47847)
26+
})
27+
})

0 commit comments

Comments
 (0)