programming-examples/js/Conditional/Write a JavaScript program to find and print the first 5 happy numbers..js
2019-11-15 12:59:38 +01:00

31 lines
609 B
JavaScript

function happy_number(num)
{
var m, n ;
var c = [] ;
while(num != 1 && c[num] !== true)
{
c[num] = true ;
m = 0 ;
while (num > 0) {
n = num % 10 ;
m += n * n ;
num = (num - n) / 10 ;
}
num = m ;
}
return (num == 1) ;
}
var cnt = 5;
var num = 1;
var f5 = '';
while(cnt-- > 0)
{
while(!happy_number(num))
num++ ;
f5 = f5+(num + ", ") ;
num++ ;
}
console.log('First 5 happy numbers are : '+f5);