krish krish - 1 year ago 69
Javascript Question

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.

Answer Source

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

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

$(document).ready(function(){
      var num = 5239;
      var i = 0;
        for(i ; i < 10000; i++){
        num = newNumber(num);
      }
        if(num == 1){
            alert("it's happy number");
          break;
        }else
      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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download