Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to determine whether the given number is a Harshad Number
A Harshad Number (also known as a Niven number) is a positive integer that is divisible by the sum of its digits. For example, 12 is a Harshad number because 12 ÷ (1 + 2) = 12 ÷ 3 = 4, which is a whole number.
Basic Approach
To check if a number is a Harshad number, we need to ?
- Calculate the sum of all digits in the number
- Check if the original number is divisible by this sum
Example
my_num = 134
remaining = sum_val = 0
print("Checking if", my_num, "is a Harshad number...")
my_num_copy = my_num
# Calculate sum of digits
while my_num > 0:
remaining = my_num % 10
sum_val = sum_val + remaining
my_num = my_num // 10
print("Sum of digits:", sum_val)
# Check if divisible by sum of digits
if my_num_copy % sum_val == 0:
print(my_num_copy, "is a Harshad number")
else:
print(my_num_copy, "isn't a Harshad number")
The output of the above code is ?
Checking if 134 is a Harshad number... Sum of digits: 8 134 isn't a Harshad number
Testing with a Harshad Number
Let's test with 12, which should be a Harshad number ?
my_num = 12
remaining = sum_val = 0
print("Checking if", my_num, "is a Harshad number...")
my_num_copy = my_num
# Calculate sum of digits
while my_num > 0:
remaining = my_num % 10
sum_val = sum_val + remaining
my_num = my_num // 10
print("Sum of digits:", sum_val)
# Check if divisible by sum of digits
if my_num_copy % sum_val == 0:
print(my_num_copy, "is a Harshad number")
else:
print(my_num_copy, "isn't a Harshad number")
The output of the above code is ?
Checking if 12 is a Harshad number... Sum of digits: 3 12 is a Harshad number
How It Works
-
Extract digits: Use
my_num % 10to get the last digit andmy_num // 10to remove it -
Sum calculation: Add each extracted digit to
sum_val -
Divisibility check: Use modulus operator to check if
original_number % digit_sum == 0
Alternative Approach Using String Conversion
A simpler method using string operations ?
def is_harshad(num):
digit_sum = sum(int(digit) for digit in str(num))
return num % digit_sum == 0
# Test with multiple numbers
test_numbers = [12, 18, 19, 21, 134]
for num in test_numbers:
if is_harshad(num):
print(f"{num} is a Harshad number")
else:
print(f"{num} is not a Harshad number")
The output of the above code is ?
12 is a Harshad number 18 is a Harshad number 19 is not a Harshad number 21 is a Harshad number 134 is not a Harshad number
Conclusion
A Harshad number is divisible by the sum of its digits. You can check this using either a while loop to extract digits or string conversion for a more concise solution. Both approaches effectively determine if a number qualifies as a Harshad number.
