Skip to content

Instantly share code, notes, and snippets.

@Rafe
Created April 11, 2013 23:43
Show Gist options
  • Save Rafe/5368127 to your computer and use it in GitHub Desktop.
Save Rafe/5368127 to your computer and use it in GitHub Desktop.
Solving fabonacci problem from http://code-warrior.herokuapp.com.

#Fabonacci

Write a function to return fabonacci sequence for n

Defination

f(n) = f(n - 1) + f(n - 2)

when n = 0, f(n) = 0, n = 1, f(n) = 1

Hint

Watch out when handling large number of n, how can you speed up the excution time?

Extra

Resolve in iteration, with fewest varible.

##Powerd by CodeWarrior

var cache = {};
var fabonacci = module.exports = function(n) {
if (n == 0) return 0;
if (n == 1) return 1;
if (!cache[n]) {
cache[n] = fabonacci(n - 1) + fabonacci(n - 2);
}
return cache[n];
}
var iterationFab = function(n) {
if (n == 0) return 0;
if (n == 1) return 1;
var a = 0, b = 1, val = 0;
for (var i = 1; i < n; i++) {
val = a + b;
a = b;
b = val;
};
return val;
}
{
"id": 2,
"name": "fabonacci",
"level": "basic",
"author": "Jimmy Chao"
}
var expect = require('expect.js');
var fab = require('./');
describe("fabonacci", function() {
it("should handle base case", function() {
expect(fab(0)).to.equal(0);
expect(fab(1)).to.equal(1);
expect(fab(2)).to.equal(1);
});
it("should return correct sequence", function() {
expect(fab(6)).to.equal(8);
expect(fab(7)).to.equal(13);
expect(fab(8)).to.equal(21);
expect(fab(9)).to.equal(34);
expect(fab(10)).to.equal(55);
});
it("should return correct number", function() {
expect(fab(14)).to.equal(377);
expect(fab(20)).to.equal(6765);
expect(fab(36)).to.equal(14930352);
expect(fab(44)).to.equal(701408733);
});
it("should fast enough to run big number", function() {
expect(fab(1000)).to.eql(4.346655768693743e+208);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment