Search code examples
javascriptnumber-theory

Check whether given number is happy or not


This is my code to check given number is a Happy number. I think I am trying wrong logic.

var num = 5239;
var sum = 0;
while (num > 0) {
  sum += Math.pow(num % 10, 2);
  num = Math.floor(num / 10);
  console.log(num)
}
console.log(sum);
if (num == 0) {
  alert("happy number")
} else {
  alert("Not happy number")
}

Please correct me to get correct result.


Solution

  • https://jsfiddle.net/g18tsjjx/1/

    If i understood what happy number is, this should be correct.

    $(document).ready(function() {
      var num = 1;
      var i = 0;
      for (i; i < 10000; i++) {
        num = newNumber(num);
      }
      num == 1 ? alert("it's happy number") : alert("it's not happy number");
    });
    
    function newNumber(num) {
      var sum = 0;
      var temp = 0;
      while (num != 0) {
        temp = num % 10;
        num = (num - temp) / 10;
        sum += temp * temp;
      }
      return sum;
    }