Skip to content

Instantly share code, notes, and snippets.

@jamescarr
Created May 22, 2010 02:57
Show Gist options
  • Save jamescarr/409709 to your computer and use it in GitHub Desktop.
Save jamescarr/409709 to your computer and use it in GitHub Desktop.
describe 'Perfect Numbers'
it 'should find 6 in a range between 2 and 10'
findPerfectNumbersInRange(2,10, function(result){
result.should.eql [6]
});
end
it 'should return 28 in a range between 20 and 30'
findPerfectNumbersInRange(20, 30, function(result){
result.should.eql [28]
});
end
it 'should return 496 in a range between 200 and 500'
findPerfectNumbersInRange(200, 500, function(result){
result.should.eql [496]
});
end
it 'should find all perfect numbers in the range 2 to 900'
findPerfectNumbersInRange(2, 900, function(result){
result.should.eql [6, 28, 496]
});
end
end
function findPerfectNumbersInRange(start, end, fnc){
var results = [];
(function(num){
perfectNumber(num, function(num){
results.push(num);
});
if(num++ < end) arguments.callee(num)
return function(){ fnc(results)}
})(start)();
}
function perfectNumber(i, fnc){
var result = 0;
for( var j = 0; j < i; j++ ) {
if(i % j == 0) result += j;
}
if( result == i) fnc(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment