Open In App

JavaScript Program to Check Whether a Number is Harshad Number

Last Updated : 08 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A Harshad number (also called Niven number) is a number that is divisible by the sum of its digits. In other words, if you take a number, sum up its digits, and if the original number is divisible by that sum, then it’s a Harshad number. For example, 18 is a Harshad number because the sum of its digits is 1 + 8 = 9, and 18 is divisible by 9.

Below are the approaches to check if a number is a Harshad number or not using JavaScript:

Check if a Number is Harshad Number using the Iterative Approach

Iterate through the digits of the number, sum them up, and then check if the original number is divisible by this sum.

Example: The below code example Uses the simple iteration Method to Check Whether a Number is a Harshad Number in JavaScript.

Javascript




function isHarshad(number) {
  let sum = 0;
  let num = number;
  while (num > 0) {
    sum += num % 10;
    num = Math.floor(num / 10);
  }
  return number % sum === 0;
}
 
console.log(isHarshad(15));


Output

false

Check if a Number is Harshad Number using inbuilt functions

Utilize mathematical properties to directly calculate whether the number is a Harshad number without iterating through its digits.

Example: The below code example Uses the simple inbuilt Method to Check Whether a Number is Harshad Number in JavaScript.

Javascript




function isHarshad(number) {
  let sumOfDigits = number
    .toString()
    .split("")
    .reduce((acc, digit) => acc + parseInt(digit), 0);
  return number % sumOfDigits === 0;
}
 
console.log(isHarshad(15));


Output

false

Check if a Number is Harshad Number using recursion

In this approach, we’ll recursively sum up the digits of the number until we get a single-digit number. Then, we’ll check if the original number is divisible by this sum. If the original number is divisible by the sum of its digits, it’s a Harshad number.

Example: The below code example Uses recursion Method to Check Whether a Number is Harshad Number in JavaScript.

Javascript




function sumOfDigits(number) {
  if (number < 10) {
    return number;
  } else {
    return (number % 10) + sumOfDigits(Math.floor(number / 10));
  }
}
 
function isHarshad(number) {
  let sum = sumOfDigits(number);
  return number % sum === 0;
}
 
console.log(isHarshad(15));


Output

false


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads