-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fibonacci optimize with Memory pattern
- Loading branch information
1 parent
a621820
commit 213636f
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
/** | ||
* Nth number of fibonacciMemory's sequence | ||
* | ||
* Returns the nth number of fibonacciMemory's sequence. | ||
* | ||
* @public | ||
* | ||
* @example | ||
* var fibonacciMemory = require('path-to-algorithms/src/others/fibonacciMemory').fibonacciMemory; | ||
* var nth = fibonacciMemory(20); | ||
* | ||
* console.log(nth); // 6765 | ||
* | ||
* @param {Number} n The nth position in fibonacciMemory's sequence | ||
* | ||
* @module others/fibonacciMemory | ||
*/ | ||
(function (exports) { | ||
'use strict'; | ||
|
||
function fibonacciMemory(n) { | ||
var i = 0; | ||
var aux = [0, 1]; | ||
while (n != i) { | ||
aux[i + 2] = aux[i] + aux[i + 1]; | ||
i++; | ||
} | ||
return aux[i]; | ||
} | ||
|
||
exports.fibonacciMemory = fibonacciMemory; | ||
})(typeof window === 'undefined' ? module.exports : window); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
var mod = require('../../src/others/fibonacciMemory.js'); | ||
var fibonacci = mod.fibonacciMemory; | ||
|
||
describe('fibonacci with Memory algorithm', function () { | ||
'use strict'; | ||
|
||
it('should return value 1 with input 1.', function () { | ||
expect(fibonacci(1)).toBe(1); | ||
}); | ||
it('should return value 6 with input 8.', function () { | ||
expect(fibonacci(6)).toBe(8); | ||
}); | ||
it('should return value 7 with input 13.', function () { | ||
expect(fibonacci(7)).toBe(13); | ||
}); | ||
it('should return value 8 with input 21.', function () { | ||
expect(fibonacci(8)).toBe(21); | ||
}); | ||
it('should return value 9 with input 34.', function () { | ||
expect(fibonacci(9)).toBe(34); | ||
}); | ||
it('should return value 10 with input 55.', function () { | ||
expect(fibonacci(10)).toBe(55); | ||
}); | ||
it('should be 135301852344706760000 with input 98.', function () { | ||
expect(fibonacci(98)).toBe(135301852344706760000); | ||
}); | ||
}); |