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)); |
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