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.
1# Take number2num = int(input("Enter a number: "))34# Calculate sum of digits5temp = abs(num)6digit_sum = 07while temp > 0:8 digit_sum += temp % 109 temp //= 101011# Check Harshad12if 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
Sum digits of abs(num).
- 2
Check digit_sum is positive before modulo.
- 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.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum