Check Harshad Number in Python

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 2 Code Examples
Digit sum

What you’ll learn

  • Harshad rule: n % digit_sum(n) == 0 for positive n.
  • Safe check that avoids division by zero and invalid inputs.
  • Range scan for 1..20 and a live preview.

Overview

A Harshad test is simple: compute digit sum once, then do one divisibility check.

Two programs

Single check for 18 and list in [1,20].

Live preview

Shows digit sum, remainder, and verdict.

Rigor

Positive-only definition and nonzero digit-sum guard.

Prerequisites

Loops, modulus, and integer division.

  • Use % 10 and // 10 to process decimal digits.
  • Know divisibility test with n % s == 0.

What is a Harshad number?

A positive number n is Harshad if it is divisible by the sum of its digits.

Example: 18 has digit sum 9, and 18 % 9 == 0.

18Harshad
11Not
Rulen % s(n) == 0

Formal divisibility

Let s(n) be decimal digit sum. For n > 0, Harshad iff n ≡ 0 (mod s(n)).

20

s(20)=2, so 20 mod 2 = 0.

Intuition

18Yes
Check
18 % 9 == 0
11No
Check
11 % 2 != 0

Takeaway: all one-digit positive numbers are Harshad.

Live preview

Positive safe integers only.

Try 1, 12, or 11.

Live result
Press “Check Harshad”.

Algorithm

Goal: check if positive n is divisible by its digit sum.

Compute digit sum

Loop through digits with % 10 and // 10.

Test divisibility

If sum > 0 and n % sum == 0, it is Harshad.

📜 Pseudocode

Pseudocode
function digit_sum_base10(n):  // n >= 0
    s = 0
    while n > 0:
        s += n mod 10
        n = floor(n / 10)
    return s

function is_harshad(n):
    if n <= 0:
        return false
    s = digit_sum_base10(n)
    if s == 0:
        return false
    return (n mod s) == 0
1

Single value: 18

Checks one number with safe guards and digit-sum helper.

python
def digit_sum_positive(n: int) -> int:
    total = 0
    while n > 0:
        total += n % 10
        n //= 10
    return total

def is_harshad(number: int) -> bool:
    if number <= 0:
        return False
    s = digit_sum_positive(number)
    if s == 0:
        return False
    return number % s == 0

number = 18
if is_harshad(number):
    print(f"{number} is a Harshad number.")
else:
    print(f"{number} is not a Harshad number.")

Explanation

For 18, digit sum is 9 and 18 is divisible by 9.

2

Harshad numbers in [1, 20]

Prints all Harshad numbers in the small interview range.

python
def digit_sum_positive(n: int) -> int:
    total = 0
    while n > 0:
        total += n % 10
        n //= 10
    return total

def is_harshad(num: int) -> bool:
    if num <= 0:
        return False
    s = digit_sum_positive(num)
    return s != 0 and num % s == 0

print("Harshad numbers in the range 1 to 20:")
for i in range(1, 21):
    if is_harshad(i):
        print(i, end=" ")
print()

Explanation

Numbers like 11 and 19 fail because they are not divisible by their digit sums.

Extensions

Large scans: use incremental digit-sum tricks for performance.

Other bases: replace base-10 extractor with base-b digits.

Interview: always mention positive-input and zero-sum guard.

❓ FAQ

A positive integer n is Harshad in base 10 if n is divisible by the sum of its decimal digits.
Yes. digit_sum(1)=1 and 1 % 1 = 0.
For n=0, digit sum becomes 0 and modulus by 0 is invalid. Standard definition uses positive n.
Yes, by using digits in that base and the same divisibility rule.
O(log10 n) digit operations plus one modulus.
Both use digit sums, but Harshad uses one sum, not repeated reduction.

🔄 Input / output examples

Change the value in Example 1 or bounds in Example 2.

ns(n)Harshad?
11Yes
123Yes
112No
189Yes

Edge cases and pitfalls

Validate positivity first to avoid invalid modulus.

Zero

n = 0

Not positive Harshad in this tutorial definition.

Negative

n < 0

Reject input unless you explicitly redefine behavior.

Base

Decimal default

Rule is base-dependent; this page uses base 10.

Large n

Big integers

Python supports them, but scan cost still grows with digit count.

⏱️ Time and space complexity

TaskTimeExtra space
One valueO(log n) digitsO(1)
Scan [1, N]O(N log N) digit workO(1)

log n here means number of decimal digits.

Summary

  • Rule: positive n is Harshad if n % digit_sum(n) == 0.
  • Code: compute sum, guard zero, then test divisibility.
  • Watch-outs: reject n <= 0 and keep base explicit.
Did you know?

Harshad numbers are also called Niven numbers. The word “Harshad” comes from Sanskrit and means “joy-giver.”

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful