Python Program to check the number is harshad number

February 3, 2022, Learn eTutorial

In this simple python program, we have to check for a Harshad number. It's a number python program.

To understand this example, you should have knowledge of the following Python programming topics:

What is a Harshad number?

A Harshad number is a number in which the sum of the digits in that number must be a divisor of that number. Which means the given number must be divisible by the sum of the digits of the number. 

For example,

  • take the number 54
  • We have to split the number into digits like 5 and 4
  • The sum of digits is 5+4 = 9
  • The condition of Harshad number is 9 must be a divisor of 54 or 54 will be divisible by 9
  • Here 54 % 9 is zero ie., it's completely divisible. The condition is true because the remainder is zero. So 54 is a Harshad number

How to do the Harshad number check in python?

In this simple python program, we use a while loop until the number is greater than zero. Then get the digit from the number using the mod (%) operator, and we add the digit to get the sum. Now divide the number by 10 to split the number and remove one digit. Then we again use the Mod operator to check the number is divisible by sum using the if condition statement in python. If its remainder is zero, then print its Harshad number.


STEP 1: Initialize a number with some predefined number.

STEP 2: Initialize the reminder and sum it to zero.

STEP 3: Copy the number to another variable to save its value.

STEP 4: Use a while loop until the number is greater than zero.

STEP 5: Calculate the remainder using the mod operator, and we get the digits of the number.

STEP 6: Add the sum as a sum and reminder, and split the number by dividing the number by 10 to remove one digit from the number.

STEP 7: Using an if condition, check the number mod sum is equal to zero.

STEP 8: If it is zero, print it's a Harshad number. Else print, not Harshad, using the python programming language.

Python Source Code

                                          num = 54;    
rem = sum = 0;    
n = num;    
while(num > 0):    
    rem = num    
    sum = sum + rem;     # calculating the sum of digits of the number
    num = num//10;    
if(n%sum == 0):    
    print(str(n) + " is a harshad number");    
    print(str(n) + " is not a harshad number");    


54 is a harshad number