Implementing the is_harshad()
Function
To implement the is_harshad()
function, we can follow these steps:
We first need to convert the input number n
to a string, so that we can iterate over its digits.
n_str = str(n)
Step 2: Calculate the sum of the digits
Next, we need to calculate the sum of the digits in the input number. We can do this using a simple loop and the int()
function to convert each character to an integer.
digit_sum = sum(int(digit) for digit in n_str)
Step 3: Check if the number is divisible by the sum of its digits
Finally, we can check if the input number n
is divisible by the sum of its digits digit_sum
. If it is, then the number is a Harshad number.
return n % digit_sum == 0
Putting it all together, the complete is_harshad()
function looks like this:
def is_harshad(n):
"""
Checks if a number is a Harshad number.
Args:
n (int): The number to be checked.
Returns:
bool: True if the number is a Harshad number, False otherwise.
"""
n_str = str(n)
digit_sum = sum(int(digit) for digit in n_str)
return n % digit_sum == 0
You can test this function by running it on various numbers, for example:
print(is_harshad(18)) ## True
print(is_harshad(27)) ## True
print(is_harshad(42)) ## True
print(is_harshad(100)) ## False
This implementation of the is_harshad()
function is simple and efficient, and it can be used to quickly determine whether a given number is a Harshad number or not.