Skip to content

Instantly share code, notes, and snippets.

@wondersloth
Last active December 19, 2015 21:59
Show Gist options
  • Save wondersloth/6024287 to your computer and use it in GitHub Desktop.
Save wondersloth/6024287 to your computer and use it in GitHub Desktop.
Happy Number Finder
(function () {
var UNHAPPY_SEQUENCE = [4, 16, 37, 58, 89, 145, 42, 20, 4];
var UNHAPPY_SEQUENCE_LENGTH = UNHAPPY_SEQUENCE.length;
function calculate(number) {
var str = '' + number;
var length = str.length;
var total = 0;
var digit;
for (var i = 0; i < length; i++) {
digit = parseInt(str[i], 10);
total += Math.pow(digit, 2);
}
return total;
}
function isUnhappySequence(sequence) {
if (sequence.length < UNHAPPY_SEQUENCE_LENGTH) {
return false;
}
var subSequence = sequence.slice(-9);
if (subSequence[0] !== 4 && subSequence[8] !== 4) {
return false;
}
var isUnhappy = true;
for (var i = 0; i < UNHAPPY_SEQUENCE_LENGTH; i++) {
isUnhappy = isUnhappy && (subSequence[i] === UNHAPPY_SEQUENCE[i]);
}
return isUnhappy;
}
function isNumberHappy(number) {
var sequence = [];
var isHappy = true;
do {
sequence.push(number);
number = calculate(number);
if (isUnhappySequence(sequence)) {
isHappy = false;
break;
}
} while (number !== 1);
return isHappy;
}
window.isNumberHappy = isNumberHappy;
})();
var number = parseInt(process.argv[2], 10);
if (!number || number <= 0) {
console.error('Invalid number, must be a postive integer.');
process.exit(1);
}
var isHappy = isNumberHappy(number);
console.log('The number \"' + number + '\":');
if (isHappy) {
console.log('Is happy! :-)');
}
else {
console.log('Is NOT happy :-(');
}
process.exit(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment