Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Harshad Numbers

List Harshad numbers from one through one hundred in Python. Students calculate decimal digit sums and test divisibility by each candidate's own derived total.

AdvancedPhase 6 - Category 1: Number LogicExample 10 of 10
harshad-numbers.py
1# Find Harshad numbers
2print("Harshad numbers 1-100:")
3
4for num in range(1, 101):
5 digit_sum = sum(int(d) for d in str(num))
6 if digit_sum > 0 and num % digit_sum == 0:
7 print(num, end=" ")
8print()

Output

...

The sample abbreviates a longer result. The program prints the intervening values; it does not print these dots.

In this one

  • Use a digit-derived divisor
  • Guard modulo zero
  • Filter positive candidates

How it works

  1. 1

    Sum digit characters of the current candidate.

  2. 2

    Require a positive sum and remainder zero.

  3. 3

    Print every accepted value in range order.

Edge cases

Does eighteen pass?

Does eighteen pass?

Yes. Eighteen is divisible by nine.

Is zero tested?

Is zero tested?

No. The candidate range begins at one.

What's going on

For each positive candidate, a generator expression builds its digit sum. The candidate prints only when dividing by that sum leaves remainder zero.

Eighteen qualifies because its digits sum to nine. Nineteen fails because its digits sum to ten. The digit_sum > 0 guard makes the divisor requirement visible, even though this positive range cannot produce a zero digit sum.

Does eighteen pass? Yes. Eighteen is divisible by nine.

Is zero tested? No. The candidate range begins at one.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is the divisor in the final test?

Pick an answer to check it.

Question 2

Does eighteen pass?

Pick an answer to check it.

Questions people ask

Does eighteen pass?

Yes. Eighteen is divisible by nine.

Is zero tested?

No. The candidate range begins at one.

What is the divisor in the final test?

The candidate's digit sum.