Definition
n % s(n) == 0
Positive n is Harshad if divisible by its digit sum.
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.
n % s(n) == 0
Positive n is Harshad if divisible by its digit sum.
Yes
1 + 8 = 9 and 18 % 9 == 0.
% 10 / // 10
Accumulate digits with modulus and integer division.
Avoid % 0
Reject nonpositive n; never divide by a zero sum.
Try any n
See digit sum, remainder, and verdict instantly.
Per check
Time tracks the number of decimal digits.
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.
It drills digit peeling and divisibility in a short warm-up — a natural follow-up after happy numbers.
Compute s(n) once, then test n % s(n).
Every one-digit positive integer is Harshad.
Loop with % // or sum over str digits.
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.
Given a positive integer n, decide whether n is divisible by the sum of its decimal digits.
# 18 → s=9 → 18 % 9 == 0 → Harshad
# 11 → s=2 → 11 % 2 != 0 → not
# 1 → s=1 → 1 % 1 == 0 → Harshad | Item | Type | Description |
|---|---|---|
n | int | Positive integer (reject n ≤ 0). |
| Return / print | bool / text | True if n is Harshad. |
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 | Idea | Notes |
|---|---|---|
| Arithmetic loop | % 10 and // 10 | Interview default — no string conversion |
| String digits | sum(int(d) for d in str(n)) | Very short in Python |
| Other bases | Peel with base b | Same rule; digits change with base |
| Goal | Pattern |
|---|---|
| Last digit | n % 10 |
| Drop digit | n //= 10 |
| Digit sum | total += n % 10 |
| Harshad test | s != 0 and n % s == 0 |
| Yes classics | 1, 12, 18, 20 |
| No classics | 11, 19 |
Same rule — pick the digit extractor that fits the interview.
% 10 / // 10Classic; no string conversion
sum(int(d)...)Short and readable in Python
peel base bSame divisibility idea, different digits
guard firstState positive-only + nonzero sum
Reach for Harshad checks when digit sums meet divisibility.
Digit loops plus a clean modulus check.
Same digit peeling; simpler stop condition.
Print all Harshad numbers in 1…N for small N.
Show that digit sum is a meaningful divisor.
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.
Positive integers only, within JavaScript safe range.
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.
Safe digit-sum helper and one divisibility test.
18Checks one number with positive-input and zero-sum guards.
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.") 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.
Reuse the same helper to filter a beginner interval.
Checks each number independently and prints only Harshad ones.
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() Numbers like 11 and 19 fail because they are not divisible by their digit sums. All one-digit values pass automatically.
Same rule with a Pythonic digit extractor.
strCompact digit sum using a generator expression over the decimal string.
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}") Converting to a string walks each character digit without a manual loop. Prefer the arithmetic version when the interviewer wants language-agnostic digit peeling.
Reject n ≤ 0 under the standard definition.
Peel with % 10 and // 10 (or sum str digits).
If s > 0 and n % s == 0, it is Harshad.
Remainder 0 → yes; otherwise no.
n = 18Trace digit summing and the final modulus for the classic Harshad example.
| Step | Working n | Action | total |
|---|---|---|---|
| 1 | 18 | 18 % 10 → 8 | 8 |
| 2 | 1 | 1 % 10 → 1 | 9 |
| 3 | 0 | loop ends | s = 9 |
| 4 | — | 18 % 9 | 0 → Harshad |
Remainder 0 → 18 is Harshad.
Where Harshad checks show up beyond the interview prompt.
Digit peeling plus a single modulus.
Example: write is_harshad(n).
Connect digit sum to modular arithmetic.
Example: 20 mod 2 = 0.
List Harshad numbers in a classroom interval.
Example: 1 to 20 list above.
% 10 / // 10 drills before harder digit problems.
Example: before Disarium.
Same idea with digits in base b.
Example: peel with n % b.
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.
Why this pattern works well in interviews and classwork.
One sentence: n divisible by sum of its digits.
One helper and one boolean — easy to whiteboard.
18 vs 11 makes verification quick.
Range scans, other bases, string digit sums.
Pro Tip: lead with the arithmetic digit loop; offer the string version if asked for idiomatic Python.
Small habits that keep Harshad solutions interview-ready.
Write a pure helper before the divisibility check.
Reject n ≤ 0 under the standard definition.
Yes and no classics catch bugs fast.
Check s != 0 before n % s.
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.
Mistakes that commonly break Harshad solutions.
Calling n % s when s is 0 (e.g. n = 0).
→ Guard positive n and nonzero sum.
Standard definition is positive integers only.
→ Reject n ≤ 0.
Repeated digit reduction is a different problem.
→ Harshad uses one sum, then divisibility.
Happy-number muscle memory can sneak in.
→ Sum digits plain — no squares.
Destroying n inside digit_sum before the modulus.
→ Work on a local copy; keep original for n % s.
Validate positivity first to avoid an invalid modulus.
digit_sum(1)=1 and 1 % 1 == 0.
Not Harshad under this tutorial definition.
n < 0Reject unless you explicitly redefine behavior.
Rule is base-dependent; this page uses base 10.
s(11)=2 and 11 % 2 != 0.
Expect 1–10, 12, 18, 20 (skip 11, 13–17, 19).
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
n % digit_sum(n) == 0.Quick Takeaway: sum the digits of positive n; if that sum divides n, the number is Harshad.
| Task | Time | Extra space |
|---|---|---|
| One value | O(log n) digits | O(1) |
| String digit sum | O(log n) | O(log n) for the string |
Scan [1, N] | O(N log N) digit work | O(1) |
log n here means the number of decimal digits.
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.
Decide Harshad the interview-friendly way.
n % s(n) == 0
DefinitionDigit peel
DigitsNo % by 0
Safety18 yes / 11 no
TestsO(log n)
AnalysisHarshad numbers are also called Niven numbers. The word “Harshad” comes from Sanskrit and means “joy-giver.”
Learn how to find the least common multiple of two integers in Python.
8 people found this page helpful