Hello students and self-learners, here is another interesting JavaScript program for you to learn the fundamentals.
In this post, I am going to write a JavaScript program to check if the entered number is a Strong number or not.
What is a Strong number?
A strong number is a number if the factorial of its digit is equal to the number itself.
Eg: 145 is a strong number. Factorial of 145 is 1! + 4! + 5! = 1 + 24 + 120 = 145
So let’s write the JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<!DOCTYPE html> <html> <head> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>JavaScript to check Strong number or not!</title> <script> function is_strong_number(){ var num = document.getElementById('num').value; sum = 0; r = 0; //store the entered number in a temp variable temp=num; //split the number and find factorial while(num){ i=1; fact=1; //get one digit from r=num%10; //factorial script while(i<=r){ fact=fact*i; i++; } //sum the factorial value sum=sum+fact; //split the next number num=Math.floor(num/10); } //check the sum value and stored temp value //if same then it's a strong number or not if(temp == sum){ document.getElementById('result').innerHTML = "<b>Result:</b> Strong Number"; }else{ document.getElementById('result').innerHTML = "<b>Result:</b> Not a Strong Number"; } } </script> </head> <body> <div class="container"> <div class="row"> <h2>JavaScript to check Strong number or not!</h2> <hr /> <div class="form-group"> <div class="form-group"> <label for="num">Number:</label> <input type="text" class="form-control" id="num" required> </div> <button type="submit" name="submit" onclick="is_strong_number()" class="btn btn-default">Submit</button> </div> <div id="result"></div> </div> </div> </body> </html> |
Just read the inline comments in the above script to understand it.
You can check the live demo here: