Advertisement
Guest User

Untitled

a guest
Jul 3rd, 2015
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. /*
  2.  
  3. A happy number is a number defined by the following process:
  4. Starting with any positive integer, replace the number by the sum of the squares of its digits,
  5. and repeat the process until the number equals 1 (where it will stay),
  6. or it loops endlessly in a cycle which does not include 1.
  7. Those numbers for which this process ends in 1 are happy numbers,
  8. while those that do not end in 1 are unhappy numbers (or sad numbers).[1]
  9.  
  10. For example, 19 is happy, as the associated sequence is:
  11. 12 + 92 = 82
  12. 82 + 22 = 68
  13. 62 + 82 = 100
  14. 12 + 02 + 02 = 1
  15.  
  16. */
  17.  
  18. var attemptedArray = [];
  19.  
  20. function formIntegerArray(num) {
  21. return num
  22. .toString()
  23. .split('')
  24. .map(function(str) { return parseInt(str); });
  25. }
  26.  
  27. function squareTotal(arr) {
  28. var total = 0;
  29.  
  30. arr.forEach(function(int) {
  31. total += int*int;
  32. });
  33.  
  34. return total;
  35. }
  36.  
  37. function logAttempt(num) {
  38. return attemptedArray.push(num);
  39. }
  40.  
  41. function alreadyAttempted(num) {
  42. return $.inArray(num, attemptedArray) !== -1;
  43. }
  44.  
  45. function isHappy(num) {
  46. var mutatedNum;
  47.  
  48. logAttempt(num);
  49. mutatedNum = squareTotal(formIntegerArray(num));
  50.  
  51. if (mutatedNum === 1) {
  52. console.log('Yeah, its happy');
  53. } else if (alreadyAttempted(mutatedNum)) {
  54. console.log('Nope, its not happy');
  55. } else {
  56. isHappy(mutatedNum);
  57. }
  58. }
  59.  
  60. // Happy Number
  61. isHappy(19);
  62.  
  63. // Sad Number
  64. isHappy(99);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement