Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ec40256

Browse files
authored
Added Fibonacci index value problem
1 parent d78fe37 commit ec40256

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

‎README.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1330,6 +1330,42 @@ function fibonacci(n){
13301330
13311331
fibonacci(12); // 144
13321332
```
1333+
### Find nth index value of fibonacci
1334+
Given a number N return the index value of the Fibonacci sequence, where the sequence is:
1335+
```
1336+
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
1337+
```
1338+
The solution is:
1339+
```
1340+
function fib(n){
1341+
var x = 0;
1342+
var y = 1;
1343+
if(n <= 2){
1344+
return n-1;
1345+
}
1346+
for(var i = 0; i < n; i++){
1347+
var tempY = y;
1348+
y = tempY + x;
1349+
x = tempY;
1350+
1351+
}
1352+
return y;
1353+
}
1354+
1355+
fib(4)
1356+
// 5
1357+
```
1358+
To better performance, we can use memoization.
1359+
```
1360+
function fib(num, memo) {
1361+
memo = memo || {};
1362+
1363+
if (memo[num]) return memo[num];
1364+
if (num <= 1) return 1;
1365+
1366+
return memo[num] = fib(num - 1, memo) + fib(num - 2, memo);
1367+
}
1368+
```
13331369
### Find Greatest Common Divisor
13341370
Using Euclidean algorithm:
13351371
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /