w3resource

JavaScript: Check a given number is self-dividing or not

JavaScript Math: Exercise-114 with Solution

Write a JavaScript program to check a given number is self-dividing number or not.

In mathematics, a self-dividing number is one that can be divided by every digit (except digit zero) within it.

Test Data:
(48) -> true
(22) -> true
(63) -> false

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript program to Check a given number is self-dividing or not</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function test(n) {
    i = n;
    num = i;
    flag = true;
    while (num > 0) {

        mod = num % 10;

        if (i % mod !== 0) {
            flag = false;
        }

        num = Math.floor(num / 10)
    }
        return flag;
}
n = 48
console.log("n = " + n)
console.log("Check the said number is self-dividing or not: " + test(n));
n = 22
console.log("n = " + n)
console.log("Check the said number is self-dividing or not: " + test(n));
n = 63
console.log("n = " + n)
console.log("Check the said number is self-dividing or not: " + test(n));

Sample Output:

n = 48
Check the said number is self-dividing or not: true
n = 22
Check the said number is self-dividing or not: true
n = 63
Check the said number is self-dividing or not: false

Flowchart:

JavaScript: Check a given number is self-dividing or not.

Live Demo:

See the Pen javascript-math-exercise-114 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Smallest number whose digits multiply to a number.
Next: Javascript Array Exercises

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

Shorten an array using its length property

A great way of shortening an array is by redefining its length property.

let array = [0, 1, 2, 3, 4, 5, 6, 6, 8, 9]
array.length = 4
// Result: [0, 1, 2, 3]

Important to know though is that this is a destructive way of changing the array. This means you lose all the other values that used to be in the array.

Ref: https://bit.ly/2LBj213