Python program that uses the modulus operator and the sum() function to check if a given number is a Harshad number

Created with Sketch.

Python program that uses the modulus operator and the sum() function to check if a given number is a Harshad number

def is_harshad(n):
    return n % sum(int(i) for i in str(n)) == 0

# Example usage
num = 18
print(is_harshad(num))

The function is_harshad(n) takes an integer as an argument, it uses the str(n) method to convert the number to a string, and then the split() method to split the string into a list of digits. It uses a list comprehension to sum up the digits, then the modulus operator to check if the number is divisible by the sum of its digits. The function returns True if the number is a Harshad number and False otherwise.

The example usage calls the is_harshad() function passing the number 18 as an argument, which returns True because 18 is divisible by the sum of its digits (1 + 8 = 9)

Here is a variant of the above program that uses the divmod() function to check if a given number is a Harshad number:

def is_harshad(n):
    return divmod(n, sum(int(i) for i in str(n)))[1] == 0

This function uses the divmod() function which returns a tuple containing the quotient and remainder of the division of the number by the sum of its digits, it then checks if the remainder is zero, if so it returns True, otherwise False.

Leave a Reply

Your email address will not be published. Required fields are marked *