Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement