How to Determine if a Number Is a Harshad Number in Python
A Harshad number (or Niven number) is a positive integer that is divisible by the sum of its digits. For example, 12 is a Harshad number because 1 + 2 = 3, and 12 is perfectly divisible by 3. These numbers are useful in recreational mathematics and digital root calculations.
This guide explains two methods to check for Harshad numbers in Python: using string conversion for readability and using integer arithmetic for performance optimization.
Understanding the Logic
To verify if a number n is a Harshad number:
- Calculate Sum of Digits: Add every individual digit of
n. - Check Divisibility: If
n \% \text{sum} == 0, it is a Harshad number. - Constraint: Harshad numbers must be positive integers (
n > 0).
Method 1: String Conversion (Readable)
The most intuitive way to sum the digits of a number in Python is to convert it to a string, iterate over the characters, convert them back to integers, and sum them.
def is_harshad_string(n):
# 1. Validation: Harshad numbers must be positive integers
if n <= 0:
return False
# 2. Convert to string to access digits
# '12' -> ['1', '2'] -> [1, 2] -> sum = 3
digits = [int(d) for d in str(n)]
digit_sum = sum(digits)
# 3. Check divisibility
return n % digit_sum == 0
# Test cases
print(f"Is 12 Harshad? {is_harshad_string(12)}") # True (1+2=3, 12%3==0)
print(f"Is 19 Harshad? {is_harshad_string(19)}") # False (1+9=10, 19%10!=0)
Output:
Is 12 Harshad? True
Is 19 Harshad? False
Method 2: Integer Arithmetic (Optimized)
Converting numbers to strings can be slow for very large numbers or in performance-critical applications. We can extract digits mathematically using the modulo operator % and integer division //.
def is_harshad_math(n):
if n <= 0:
return False
original_n = n
digit_sum = 0
# 1. Extract digits loop
while n > 0:
digit_sum += n % 10 # Get last digit
n //= 10 # Remove last digit
# 2. Check divisibility using the original number
return original_n % digit_sum == 0
# Test cases
print(f"Is 21 Harshad? {is_harshad_math(21)}") # True (2+1=3, 21%3==0)
print(f"Is 200 Harshad? {is_harshad_math(200)}") # True (2+0+0=2, 200%2==0)
Output:
Is 21 Harshad? True
Is 200 Harshad? True
The mathematical approach is generally faster because it avoids the overhead of memory allocation for string conversion.
Practical Application: Harshad Sequences
Harshad numbers often appear in sequences. Let's create a generator to find the first N Harshad numbers.
def is_harshad_math(n):
if n <= 0:
return False
original_n = n
digit_sum = 0
# 1. Extract digits loop
while n > 0:
digit_sum += n % 10 # Get last digit
n //= 10 # Remove last digit
# 2. Check divisibility using the original number
return original_n % digit_sum == 0
def generate_harshad_numbers(limit):
count = 0
num = 1
result = []
while count < limit:
if is_harshad_math(num):
result.append(num)
count += 1
num += 1
return result
# Get first 10 Harshad numbers
sequence = generate_harshad_numbers(10)
print(f"First 10 Harshad Numbers: {sequence}")
Output:
First 10 Harshad Numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Conclusion
To check for Harshad numbers in Python:
- Use String Conversion (
sum(int(d) for d in str(n))) for simplicity and readability. - Use Integer Arithmetic (
while n > 0) for performance efficiency. - Validate Inputs to ensure
n > 0, as division by zero or negative number logic can cause errors.