Editor

Python Program to Check a Harshad Number

Beginner · Numbers

A Harshad number, also called a Niven number, is divisible by the sum of its own digits. 156 is a Harshad number: its digits add up to 1 + 5 + 6 = 12, and 156 divided by 12 is exactly 13. The name comes from Sanskrit and means great joy.

Program

harshad_number.py
num = 156 # or: num = int(input("Enter a number: "))
digit_sum = 0
temp = num # work on a copy so num stays unchanged
while temp > 0:
digit_sum += temp % 10
temp //= 10
print(f"Sum of the digits of {num}: {digit_sum}")
if digit_sum > 0 and num % digit_sum == 0:
print(f"{num} / {digit_sum} = {num // digit_sum}, so {num} is a Harshad number")
else:
print(num, "is not a Harshad number")
Output
Sum of the digits of 156: 12
156 / 12 = 13, so 156 is a Harshad number

How it works

  1. The while loop adds up the digits of the number with % 10 and //= 10.
  2. num % digit_sum == 0 checks that the number divides by its digit sum with no remainder.
  3. The digit_sum > 0 test comes first so that 0, whose digit sum is 0, never causes a division by zero.
  4. For a Harshad number the program also prints the division, here 156 / 12 = 13.

Another way to write it

Harshad numbers from 1 to 100

Harshad numbers from 1 to 100
def digit_sum(n):
return sum(int(d) for d in str(n))
harshad = [n for n in range(1, 101) if n % digit_sum(n) == 0]
print("Harshad numbers from 1 to 100:")
print(harshad)
print("How many:", len(harshad))
Output
Harshad numbers from 1 to 100:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42, 45, 48, 50, 54, 60, 63, 70, 72, 80, 81, 84, 90, 100]
How many: 33

Every one-digit number is a Harshad number, since it divides itself, and the next ones are 10, 12, 18, 20 and 21.

Try it yourself

Check 1729, the famous taxicab number, to see whether it is also a Harshad number.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises