Skip to content

Commit f97bdc3

Browse files
authored
added Problem 25
1 parent 5f601fa commit f97bdc3

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Project-Euler/Problem025.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* Problem 20 - 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 fibonacci(n) {
32+
// Creates an array of Fibonacci numbers using the Fibonacci formula. Returns the nth element of the array.
33+
if (n === 1) {
34+
return 0
35+
}
36+
else if (n === 2) {
37+
return 1
38+
}
39+
else {
40+
series = [0,1]
41+
for (let i = 2; i <= n; i++) {
42+
series.push(sequence[i-1]+sequence[i-2])
43+
}
44+
return sequence[n]
45+
}
46+
}
47+
48+
function fibonacciIndex(n = 1000) {
49+
// Computes incrementing Fibonacci numbers starting from 3 and checks if its length is equal to n. Returns the term of the sequence in which it happens first.
50+
let digits = 0
51+
let index = 2
52+
while (digits < n) {
53+
index += 1
54+
digits = fibonacci(index).toString().length
55+
}
56+
return index
57+
}
58+
59+
export { fibonacciIndex }

0 commit comments

Comments
 (0)