Check Harshad Number in Python

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Digit sum

What You’ll Learn

A Harshad (Niven) number is divisible by the sum of its own digits. This tutorial covers the rule, safe guards, a live preview, worked Python examples, edge cases, and complexity.

Definition

n % s(n) == 0

Positive n is Harshad if divisible by its digit sum.

Classic 18

Yes

1 + 8 = 9 and 18 % 9 == 0.

Digit Peel

% 10 / // 10

Accumulate digits with modulus and integer division.

Zero Guard

Avoid % 0

Reject nonpositive n; never divide by a zero sum.

Live Preview

Try any n

See digit sum, remainder, and verdict instantly.

O(log n)

Per check

Time tracks the number of decimal digits.

Introduction

A Harshad number (also called a Niven number) is a positive integer that is divisible by the sum of its decimal digits. Example: 18 has digit sum 9, and 18 % 9 == 0.

Interview prompts usually ask for a boolean check or a small range listing. The core work is one digit-sum pass, a nonzero-sum guard, then a single modulus.

Why it matters?

It drills digit peeling and divisibility in a short warm-up — a natural follow-up after happy numbers.

Key Highlights

One Digit Sum

Compute s(n) once, then test n % s(n).

1–9 Always Yes

Every one-digit positive integer is Harshad.

Two Styles

Loop with % // or sum over str digits.

Positive Only

Reject 0 and negatives by definition.

In short: for positive n, sum the digits, guard against zero, and check whether n is divisible by that sum.

📝 Problem & Approach

Given a positive integer n, decide whether n is divisible by the sum of its decimal digits.

python
# 18 → s=9  → 18 % 9 == 0  → Harshad
# 11 → s=2  → 11 % 2 != 0  → not
# 1  → s=1  → 1 % 1 == 0   → Harshad

Inputs & Outputs

ItemTypeDescription
nintPositive integer (reject n ≤ 0).
Return / printbool / textTrue if n is Harshad.

Minimal workflow

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

Method comparison

MethodIdeaNotes
Arithmetic loop% 10 and // 10Interview default — no string conversion
String digitssum(int(d) for d in str(n))Very short in Python
Other basesPeel with base bSame rule; digits change with base

⚡ Quick Reference

GoalPattern
Last digitn % 10
Drop digitn //= 10
Digit sumtotal += n % 10
Harshad tests != 0 and n % s == 0
Yes classics1, 12, 18, 20
No classics11, 19

📋 Loop vs String vs Other Bases

Same rule — pick the digit extractor that fits the interview.

Arithmetic
% 10 / // 10

Classic; no string conversion

String sum
sum(int(d)...)

Short and readable in Python

Other base
peel base b

Same divisibility idea, different digits

Interview tip
guard first

State positive-only + nonzero sum

Context

When This Problem Shows Up

Reach for Harshad checks when digit sums meet divisibility.

  1. Interview warm-ups

    Digit loops plus a clean modulus check.

  2. After happy numbers

    Same digit peeling; simpler stop condition.

  3. Range listing tasks

    Print all Harshad numbers in 1…N for small N.

  4. Teaching divisibility

    Show that digit sum is a meaningful divisor.

  5. Positive-only scope

    State that 0 / negatives are out of scope.

Key benefit: a tiny boolean problem that still forces careful input validation and a zero-sum guard.

🔮 Live Preview

Positive integers only, within JavaScript safe range.

Try 1, 12, 11, or 20.

Live result
Press “Check Harshad”.

Examples Gallery

Three complete Python programs — single check for 18, range 1–20, and a string digit-sum style. Click View Output to reveal sample console results.

📚 Getting Started

Safe digit-sum helper and one divisibility test.

Example 1 — Single Value: 18

Checks one number with positive-input and zero-sum guards.

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.")

How It Works

For 18, digit sum is 9 and 18 is divisible by 9. The early returns keep nonpositive inputs and a zero sum from reaching the modulus.

⚡ Range Output

Reuse the same helper to filter a beginner interval.

Example 2 — Harshad Numbers in [1, 20]

Checks each number independently and prints only Harshad ones.

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()

How It Works

Numbers like 11 and 19 fail because they are not divisible by their digit sums. All one-digit values pass automatically.

⚙️ String Digit Sum

Same rule with a Pythonic digit extractor.

Example 3 — Sum Digits via str

Compact digit sum using a generator expression over the decimal string.

python
def digit_sum_str(n: int) -> int:
    return sum(int(d) for d in str(n))


def is_harshad_str(n: int) -> bool:
    if n <= 0:
        return False
    s = digit_sum_str(n)
    return s != 0 and n % s == 0


for value in (18, 11, 1, 20):
    label = "Harshad" if is_harshad_str(value) else "not Harshad"
    print(f"{value}: {label}")

How It Works

Converting to a string walks each character digit without a manual loop. Prefer the arithmetic version when the interviewer wants language-agnostic digit peeling.

🧠 How the Algorithm Decides

1

Validate input

Reject n ≤ 0 under the standard definition.

Guard
2

Sum digits

Peel with % 10 and // 10 (or sum str digits).

s(n)
3

Test divisibility

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

Verdict
=

Harshad or not

Remainder 0 → yes; otherwise no.

🔎 Worked Walkthrough — n = 18

Trace digit summing and the final modulus for the classic Harshad example.

StepWorking nActiontotal
11818 % 10 → 88
211 % 10 → 19
30loop endss = 9
418 % 90 → Harshad

Remainder 0 → 18 is Harshad.

Use Cases

Where Harshad checks show up beyond the interview prompt.

1. Interview Warm-Ups

Digit peeling plus a single modulus.

Example: write is_harshad(n).

2. Teaching Divisibility

Connect digit sum to modular arithmetic.

Example: 20 mod 2 = 0.

3. Range Filters

List Harshad numbers in a classroom interval.

Example: 1 to 20 list above.

4. Digit Practice

% 10 / // 10 drills before harder digit problems.

Example: before Disarium.

5. Base Variants

Same idea with digits in base b.

Example: peel with n % b.

6. Validation Habits

Practice rejecting invalid inputs early.

Example: n ≤ 0 → false.

Pro Tip: say “Harshad means divisible by digit sum” and mention the zero-sum guard before coding.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Clear Rule

    One sentence: n divisible by sum of its digits.

  2. 2. Tiny Code

    One helper and one boolean — easy to whiteboard.

  3. 3. Famous Tests

    18 vs 11 makes verification quick.

  4. 4. Easy Extensions

    Range scans, other bases, string digit sums.

Pro Tip: lead with the arithmetic digit loop; offer the string version if asked for idiomatic Python.

Usage Tips

Small habits that keep Harshad solutions interview-ready.

  1. 1. Extract Digit Sum First

    Write a pure helper before the divisibility check.

  2. 2. Guard Positive n

    Reject n ≤ 0 under the standard definition.

  3. 3. Spot-Check 18 and 11

    Yes and no classics catch bugs fast.

  4. 4. Never Mod by Zero

    Check s != 0 before n % s.

  5. 5. Name the Base

    Say “base 10” so other-base follow-ups are clear.

Pro Tip: all digits 1–9 are Harshad — say that when asked about the smallest cases.

Common Pitfalls

Mistakes that commonly break Harshad solutions.

  1. 1. Modulus by Zero

    Calling n % s when s is 0 (e.g. n = 0).

    → Guard positive n and nonzero sum.

  2. 2. Accepting Negatives

    Standard definition is positive integers only.

    → Reject n ≤ 0.

  3. 3. Confusing With Digital Root

    Repeated digit reduction is a different problem.

    → Harshad uses one sum, then divisibility.

  4. 4. Squaring Digits by Habit

    Happy-number muscle memory can sneak in.

    → Sum digits plain — no squares.

  5. 5. Mutating the Original n

    Destroying n inside digit_sum before the modulus.

    → Work on a local copy; keep original for n % s.

Edge Cases

Validate positivity first to avoid an invalid modulus.

n = 1

One-digit yes

digit_sum(1)=1 and 1 % 1 == 0.

n = 0

Not positive

Not Harshad under this tutorial definition.

Negative

n < 0

Reject unless you explicitly redefine behavior.

Base

Decimal default

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

11

Classic no

s(11)=2 and 11 % 2 != 0.

Range

1 to 20

Expect 1–10, 12, 18, 20 (skip 11, 13–17, 19).

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Definition. Positive n is Harshad in base 10 iff n ≡ 0 (mod s(n)).
  • One-digit. Every integer from 1 to 9 is Harshad.
  • Also Niven. Same concept under another common name.
  • Not digital root. Harshad stops after one sum; digital root repeats until one digit.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Classify classics

  • 1, 12, 18, 20 → Harshad
  • 11, 19 → not

2. Match both styles

  • Loop vs string digit sum
  • Assert identical booleans

3. Range 1 to 100

  • List all Harshad numbers
  • Compare with a known list

4. Print the check

  • Show n, s(n), and n % s(n)
  • Great for debugging interviews

Notes

  • 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 the base explicit.
  • Per check: O(number of digits) time with O(1) extra space.

Quick Takeaway: sum the digits of positive n; if that sum divides n, the number is Harshad.

⏱️ Time and Space Complexity

TaskTimeExtra space
One valueO(log n) digitsO(1)
String digit sumO(log n)O(log n) for the string
Scan [1, N]O(N log N) digit workO(1)

log n here means the number of decimal digits.

Wrap Up

🎉 Conclusion

Harshad (Niven) numbers are positive integers divisible by their digit sum. Keep the check tiny: validate input, sum digits, guard against zero, then take the modulus.

Practice the three examples above, then continue to LCM for another classic number-theory warm-up.

Remainder 0 means Harshad; never run the modulus when the digit sum is 0.

💡 Best Practices

✅ Do

  • Write a pure digit-sum helper
  • Guard positive n and nonzero sum
  • Test 18, 11, and 1
  • State base 10 explicitly
  • Prefer % // for interviews

❌ Don’t

  • Modulus by a zero digit sum
  • Accept 0 or negatives silently
  • Square digits (that is happy numbers)
  • Confuse with digital-root reduction
  • Mutate n before the final % check

Key Takeaways

Knowledge Unlocked

Five things to remember about Harshad numbers

Decide Harshad the interview-friendly way.

5
Core concepts
Σ 02

Sum

Digit peel

Digits
0 03

Guard

No % by 0

Safety
18 04

Classic

18 yes / 11 no

Tests
O 05

Cost

O(log n)

Analysis

❓ Frequently Asked Questions

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. All one-digit positive numbers are Harshad.
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. This page uses base 10.
O(log10 n) digit operations plus one modulus — linear in the number of digits.
Both use digit sums, but Harshad uses one sum and a divisibility check, not repeated reduction to a single digit.
No. digit_sum(11)=2 and 11 % 2 != 0.
Both work. %10 //10 is classic interview style; sum(int(d) for d in str(n)) is shorter in Python.

Did you Know? 🔊

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

Continue to LCM

Learn how to find the least common multiple of two integers in Python.

LCM tutorial →

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