Last active
August 29, 2015 14:22
-
-
Save paultannenbaum/b0a51121829decb9b048 to your computer and use it in GitHub Desktop.
Question: Using Javascript, create a function that can tell whether a number is happy number or not by logging it to the console. You can use a library like underscore or jQuery for utility methods if desired.
This file contains hidden or 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
| /* | |
| A happy number is a number defined by the following process: | |
| Starting with any positive integer, replace the number by the sum of the squares of its digits, | |
| and repeat the process until the number equals 1 (where it will stay), | |
| or it loops endlessly in a cycle which does not include 1. | |
| Those numbers for which this process ends in 1 are happy numbers, | |
| while those that do not end in 1 are unhappy numbers (or sad numbers).[1] | |
| For example, 19 is happy, as the associated sequence is: | |
| 12 + 92 = 82 | |
| 82 + 22 = 68 | |
| 62 + 82 = 100 | |
| 12 + 02 + 02 = 1 | |
| */ | |
| var attemptedArray = []; | |
| function formIntegerArray(num) { | |
| return num | |
| .toString() | |
| .split('') | |
| .map(function(str) { return parseInt(str); }); | |
| } | |
| function squareTotal(arr) { | |
| var total = 0; | |
| arr.forEach(function(int) { | |
| total += int*int; | |
| }); | |
| return total; | |
| } | |
| function logAttempt(num) { | |
| return attemptedArray.push(num); | |
| } | |
| function alreadyAttempted(num) { | |
| return $.inArray(num, attemptedArray) !== -1; | |
| } | |
| function isHappy(num) { | |
| var mutatedNum; | |
| logAttempt(num); | |
| mutatedNum = squareTotal(formIntegerArray(num)); | |
| if (mutatedNum === 1) { | |
| console.log('Yeah, its happy'); | |
| } else if (alreadyAttempted(mutatedNum)) { | |
| console.log('Nope, its not happy'); | |
| } else { | |
| isHappy(mutatedNum); | |
| } | |
| } | |
| // Happy Number | |
| isHappy(19); | |
| // Sad Number | |
| isHappy(99); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment