Coding Harshad Number Detection in Python
Now that we understand the concept of Harshad numbers and the digit sum approach to identify them, let's dive into the implementation details in Python.
Detecting Harshad Numbers in a Range
To detect Harshad numbers within a given range, we can use the is_harshad()
function from the previous section and apply it to each number in the range. Here's an example:
def find_harshad_numbers(start, end):
"""
Finds all Harshad numbers within a given range.
Args:
start (int): The starting number of the range.
end (int): The ending number of the range.
Returns:
list: A list of Harshad numbers found in the range.
"""
harshad_numbers = []
for num in range(start, end + 1):
if is_harshad(num):
harshad_numbers.append(num)
return harshad_numbers
## Example usage
print(find_harshad_numbers(1, 100))
## Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 27, 30, 36, 40, 45, 48, 50, 54, 60, 63, 70, 72, 80, 81, 84, 90, 100]
In this example, the find_harshad_numbers()
function takes a start and end value for the range, and returns a list of all Harshad numbers found within that range.
Generating Harshad Numbers
You can also write a function to generate Harshad numbers up to a certain limit. Here's an example:
def generate_harshad_numbers(limit):
"""
Generates Harshad numbers up to a given limit.
Args:
limit (int): The upper limit for the Harshad numbers.
Returns:
list: A list of Harshad numbers up to the given limit.
"""
harshad_numbers = []
n = 1
while n <= limit:
if is_harshad(n):
harshad_numbers.append(n)
n += 1
return harshad_numbers
## Example usage
print(generate_harshad_numbers(1000))
## Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 27, 30, 36, 40, 45, 48, 50, 54, 60, 63, 70, 72, 80, 81, 84, 90, 100, 102, 108, 110, 114, 120, 126, 132, 135, 140, 144, 150, 162, 171, 180, 189, 192, 195, 198, 200, 201, 204, 207, 210, 216, 219, 220, 225, 228, 234, 240, 243, 252, 270, 279, 280, 288, 297, 300, 306, 310, 315, 318, 324, 330, 333, 336, 340, 342, 345, 360, 363, 369, 370, 378, 380, 384, 390, 396, 400, 405, 408, 414, 420, 423, 432, 440, 441, 450, 459, 460, 468, 470, 480, 486, 490, 495, 504, 507, 510, 513, 520, 522, 525, 528, 540, 549, 560, 567, 570, 576, 580, 585, 588, 594, 600]
In this example, the generate_harshad_numbers()
function takes an upper limit as input and generates a list of all Harshad numbers up to that limit.
By combining the is_harshad()
function with these utility functions, you can easily detect and work with Harshad numbers in your Python projects.