# Python program to determine whether the given number is a Harshad Number

PythonServer Side ProgrammingProgramming

When it is required to determine if a given number is a Harshad number or not, a simple loop and ‘%’ operator, ‘+’ operator and ‘//’ operators can be used.

A Harshad number is also known as a Niven number. It is a number whoses base is an integer that can be divided by the sum of its digits when it is written as that base value.

Below is a demonstration for the same −

## Example

Live Demo

my_num = 134
remaining = sum_val = 0
print("A copy of the number to be checked is being made...")
my_num_copy = my_num;
while(my_num > 0):
remaining = my_num%10;
sum_val = sum_val + remaining;
my_num = my_num//10;
if(my_num_copy % sum_val == 0):
print(str(my_num_copy) + " is a Harshad number");
else:
print(str(my_num_copy) + " isn't a Harshad number");

## Output

A copy of the number to be checked is being made...
134 isn't a Harshad number

## Explanation

• A number is defined.
• Another sum variable is assigned the value 0.
• The number is checked to be greater than 0, and modulus operation is performed on it.
• This result is added to the ‘sum’ and the number is again floor divided by 10.
• If the remainder when the number and sum are divided is 0, it is considered as a Harshad number.
• Otherwise, it is not considered as a Harshad number.
Published on 12-Mar-2021 12:14:12