Finding out the Harshad number JavaScript


Harshad numbers are those numbers which are exactly divisible by the sum of their digits. Like the number 126, it is completely divisible by 1+2+6 = 9.

  • All single digit numbers are harshad numbers.

  • Harshad numbers often exist in consecutive clusters like [1,2,3,4,5,6,7,8,9,10], [110,111,112], [1010, 1011, 1012].

Our job is to write a function that takes in a Number as input checks whether it’s a harshad number or not, if not then returns -1 otherwise it returns the length of streak of consecutive harshad cluster.

For example −

harshadNum(1014) = harshadNum(1015) = harshadNum(1016) = harshadNum(1017) = 4
harshadNum(1) = 10
harshadNum(12) = 1
harshadNum(23) = -1

Let’s break this problem into two major functions,

  • isHarshad() →  takes in a number num and returns a boolean depending upon whether the number is harshad or not.

  • harshadNum() → main function that takes in the actual number, makes call to isHarshad() at various points and returns the length of streak.

Coding the isHarshad function() −

const isHarshad = (num) => {
   let sum = 0, temp = num;
   while(temp){
      sum += temp % 10;
      temp = Math.floor(temp/10);
   }
   return num % sum === 0;
}

Pretty simple iterative function that returns a boolean

Now let’s code the harshadNum() function −

const harshadNum = (number) => {
   //if the input is not harshad return -1
   if(!isHarshad(number)){
      return -1;
   }
   let streak = 1, prev = number-1, next = number+1;
   //check preceding streak
   while(isHarshad(prev) && prev > 0){
      streak++;
      prev--;
   }
   //check succeeding streak
   while(isHarshad(next)){
      streak++;
      next++;
   }
   return streak;
};
console.log(harshadNum(1014));

Understanding the above code −

  • Check whether the input is harshad or not, if not stop the function and return -1;

  • Run one loop backwards, one forwards while we keep getting harshad numbers,simultaneously keep updating the streak

  • Lastly return the streak

Following is the complete code −

Example

const isHarshad = (num) => {
   let sum = 0, temp = num;
   while(temp){
      sum += temp % 10;
      temp = Math.floor(temp/10);
   }
   return num % sum === 0;
}
const harshadNum = (number) => {
   //if the input is not harshad return -1
   if(!isHarshad(number)){
      return -1;
   }
   let streak = 1, prev = number-1, next = number+1;
   //check preceding streak
   while(isHarshad(prev) && prev > 0){
      streak++;
      prev--;
   }
   //check succeeding streak
   while(isHarshad(next)){
      streak++;
      next++;
   }
   return streak;
};
console.log(harshadNum(1014));

Output

Output for this code in the console will be −

4

Updated on: 19-Aug-2020

376 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements