JavaScript: Find and print the first 5 happy numbers
JavaScript Conditional Statement and loops: Exercise-8 with Solution
Happy Numbers:
According to Wikipedia a happy number is 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 equals 1 (where it will stay), or it loops endlessly in a cycle which 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)". Write a JavaScript program to find and print the first 5 happy numbers.
Pictorial Presentation:
Sample Solution:-
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Happy Number</title>
</head>
<body>
</body>
</html>
JavaScript Code:
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);
Sample Output:
First 5 happy numbers are : 1, 7, 10, 13, 19,
Flowchart:
Live Demo:
See the Pen javascript-conditional-statements-and-loops-exercise-8 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program which iterates the integers from 1 to 100.
Next: Write a JavaScript program to find the armstrong numbers of 3 digits.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
JavaScript: Tips of the Day
How to insert an item into an array at a specific index (JavaScript)?
What you want is the splice function on the native array object.
arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert). In this example we will create an array and add an element to it into index 2:
var arr = []; arr[0] = "Jani"; arr[1] = "Hege"; arr[2] = "Stale"; arr[3] = "Kai Jim"; arr[4] = "Borge"; console.log(arr.join()); arr.splice(2, 0, "Lene"); console.log(arr.join());
Ref: https://bit.ly/2BXbp04
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework