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


JavaScript Program to Check Whether a Number is Harshad Number

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:

Table of Content

  • Iterative Approach
  • Using inbuilt functions
  • Using recursion

Similar Reads

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....

Check if a Number is Harshad Number using inbuilt functions

...

Check if a Number is Harshad Number using recursion

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

Contact Us