Check for a self-dividing number in JavaScript


We are required to write a JavaScript function that takes in a number and determines whether or not it is a self−dividing number.

  • A self−dividing number is a number that is divisible by every digit it contains.

  • It should output “This number is self−dividing” if it is otherwise, it should output “This number is NOT self−dividing”.

For example,

  • 128 is a self−dividing number because 1, 2, and 8 are all divisors of 128.

  • Another example, 102 is not a self−diving number because it contains a digit 0.

  • As a 3rd example, 26 is not a self−dividing number, because it’s not divisible by 6.

Example

The code for this will be −

const num1 = 128;
const num2 = 102;
const num3 = 26;
const selfDivisible = num =>{
   let n = num;
   while(num){
      let temp = num % 10;
      if(n % temp !== 0){
         return false;
      };
      num = Math.floor(num/10);
   };
   return true;
};
console.log(selfDivisible(num1));
console.log(selfDivisible(num2));
console.log(selfDivisible(num3));

Output

And the output in the console will be −

true
false
false

Updated on: 21-Nov-2020

160 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements