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

Harshad Number Check

Check divisibility by a number's digit sum with Python. Students trace Harshad logic, absolute values, and a guard that prevents a zero-divisor error.

IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 13 of 14
harshad-number-check.py
1# Take number
2num = int(input("Enter a number: "))
3
4# Calculate sum of digits
5temp = abs(num)
6digit_sum = 0
7while temp > 0:
8 digit_sum += temp % 10
9 temp //= 10
10
11# Check Harshad
12if digit_sum > 0 and abs(num) % digit_sum == 0:
13 print("Harshad number")
14else:
15 print("Not a Harshad number")

Output

Enter a number: 18
Harshad number

In this one

  • Derive a divisor from digits
  • Guard a zero divisor
  • Check a magnitude consistently

How it works

  1. 1

    Sum digits of abs(num).

  2. 2

    Check digit_sum is positive before modulo.

  3. 3

    Compare abs(num) % digit_sum with zero.

Edge cases

Why check digit_sum > 0 first?

Why check digit_sum > 0 first?

It prevents modulo by zero for input zero.

Does -18 pass here?

Does -18 pass here?

Yes. Its absolute value is divisible by its digit sum.

What's going on

A Harshad check divides the positive magnitude by the sum of its decimal digits. The while loop builds that digit sum using remainder and floor division.

The final condition checks digit_sum > 0 before taking a remainder by it. With 18, the sum is nine and the remainder is zero. abs means negative inputs are treated by magnitude, while zero is rejected rather than used as a zero divisor.

Why check digit_sum > 0 first? It prevents modulo by zero for input zero.

Does -18 pass here? Yes. Its absolute value is divisible by its digit sum.

Quiz

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

Question 1

What is the digit sum of 18?

Pick an answer to check it.

Question 2

Why check digit_sum > 0 first?

Pick an answer to check it.

Questions people ask

Why check digit_sum > 0 first?

It prevents modulo by zero for input zero.

Does -18 pass here?

Yes. Its absolute value is divisible by its digit sum.

What is the digit sum of 18?

9.