krish
krish

Reputation: 1117

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.

Upvotes: 2

Views: 1905

Answers (6)

Penny Liu
Penny Liu

Reputation: 17388

According to @Kevin expound, I created a JS version:

function isHappy(n) {
  const next = (n) => {
    let ret = 0;
    for (const digit of `${n}`) {
      ret += (+digit) ** 2;
    }
    return ret;
  };
  while (n !== 1 && n !== 4) n = next(n);
  return n === 1;
}

console.log(isHappy(5239));
console.log(isHappy(19));

Upvotes: 1

manonthemat
manonthemat

Reputation: 6251

I just came across happy numbers today in a job interview. Here's the solution I came up with.

Even though I use recursion, using the set of seen numbers should prevent a stack overflow (and a potential endless loop in some cases).

'use strict';

function happyNumber(n, unluckySet = new Set()) {
  const digitChars = n.toString().split('');
  let sum = 0;
  digitChars.forEach( digitChar => {
    sum += Math.pow(Number.parseInt(digitChar), 2);
  });
  if (sum === 1) return true; // lucky!
  if (unluckySet.has(sum)) return false; // we're unlucky
  unluckySet.add(sum);
  return happyNumber(sum, unluckySet);
}

// print all happy numbers in range 0..100
for (let i = 0; i <= 100; ++i) {
  if (happyNumber(i)) console.log(`${i} is a happy number`);
}

// this still should not cause a stack overflow
const largeHappyNum = 1234567894;
console.log(largeHappyNum, 'is happy:', happyNumber(largeHappyNum));

Upvotes: 1

manoj kiran
manoj kiran

Reputation: 114

this is code for any number. like number can be 3,4,5,6,7,8,9 digits. code helps you.

<!DOCTYPE html>
<html>
<title> Happy number</title>
<head>
<script>
function fun(){

var input = document.myform.t1.value;
do{

var output = [];
var sNumber = input.toString();
var len = sNumber.length;

var sum = 0;

for (var i = 0; i < len; i++) 
{
    output.push(+sNumber.charAt(i));
}


var j;
var ret= [];
var outlen = output.length;
    for (j = 0; j < outlen; j++) 
    {
        ret.push(output[j] * output[j]);
    }
    
var sum = ret.reduce(getSum);
     
input = sum;

}while(input >= 9);

if(input == 1)
{
document.getElementById("para1").innerHTML = (" given number is happynumber");
}
else
{ 
document.getElementById("para1").innerHTML = ("not happy number");
}
}
function getSum(total, num) {
    return total + num;}
</script>
</head>
<body>
<center>
<form name="myform" method="post" onsubmit="fun(); return false;">

<table border="1">

<tr>
<th colspan="2"> Happy Number </th>  
</tr>

<tr>
<th> input number : </th>
<td> <input type="text" name="t1" id="text1" pattern="[0-9]{2,}" title="only numbers allowed" ></td>
</tr>

<tr>
<td colspan="2"> <center><button onclick="fun()">alert</button></center></td>
</tr>

<tr>
<td colspan="2"> <center>  <p id="para1"  style="color:red;"> </p> </center></td>
</tr>

</table>
</form>
</center>
</body>
</html>

Upvotes: 0

berkay kılı&#231;
berkay kılı&#231;

Reputation: 160

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;
}

Upvotes: 2

Artsrun Hakobyan
Artsrun Hakobyan

Reputation: 112

According to wikipedia

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 either equals 1 (where it will stay), or it loops endlessly in a cycle that 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). wikipedia Happy number

I created recursive function isHappy to which we will pass our number,so
taking into the account Happy Number definition and that javascript will trow Uncaught RangeError: Maximum call stack size exceeded when we will endlessly loop , we will put function inside of try...catch block , So here is final Code

//Our Recursive Function
function isHappy(number){

   var output = [],
   sNumber = number.toString();

for (var i = 0, len = sNumber.length; i < len; i += 1) {

    output.push(+sNumber.charAt(i));//converting into number 

  }
  var sum=0;

for(var i=0;i<output.length;i++){
    sum+=Math.pow(output[i],2);
   }

if(sum!==1){
  isHappy(sum);

  }

}



 try{
      isHappy(number);//call the function with given number 
      alert('happy')

    }catch(err){
    alert('unhappy')
    }

Upvotes: 1

Ajna
Ajna

Reputation: 71

I fear you are misreading the condition: it should first of all check for the final number being === 1.

And you should not proceed with just an iteration, but go on until you either reach 1 or meet an already parsed number. I would recommend using a hash to keep track of the already seen numbers.

Just not to do some homework for free, a nice example with recursion here.

Upvotes: 0

Related Questions