Skip to content

Instantly share code, notes, and snippets.

@nonsensery
Created May 27, 2015 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nonsensery/1b48da5316a092dc7312 to your computer and use it in GitHub Desktop.
Save nonsensery/1b48da5316a092dc7312 to your computer and use it in GitHub Desktop.
var bigInt = require('big-integer');
/**
* @class Grains
*
* Computes the number of grains on the squares of a
* chess board, starting with one grain on the first
* square, and doubling with each successive square.
*/
function Grains() {
// no op!
}
/**
* Gets the number of grains on the nth square.
*/
Grains.prototype.square = function(num) {
return bigInt(2).pow(num - 1);
};
/**
* Gets the total number of grains on all squares.
*/
Grains.prototype.total = function () {
var total = bigInt(0);
for (var squareNum = 1; squareNum <= 64; ++squareNum) {
total = total.add(this.square(squareNum));
}
return total;
};
module.exports = Grains;
var Grains = require('./grains');
describe("Grains", function () {
var grains = new Grains();
it("square 1", function () {
expect(grains.square(1).toString()).toEqual('1');
});
it("square 2", function () {
expect(grains.square(2).toString()).toEqual('2');
});
it("square 3", function () {
expect(grains.square(3).toString()).toEqual('4');
});
it("square 4", function () {
expect(grains.square(4).toString()).toEqual('8');
});
it("square 16", function () {
expect(grains.square(16).toString()).toEqual('32768');
});
it("square 32", function () {
expect(grains.square(32).toString()).toEqual('2147483648');
});
it("square 64", function () {
expect(grains.square(64).toString()).toEqual('9223372036854775808');
});
it("total", function () {
expect(grains.total().toString()).toEqual('18446744073709551615');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment