Python Program to Check If a Number is a Harshad Number
Harshad Numbers can be divided by the sum of its digits. They are also called Niven Numbers. For instance, 18 is a Harshad Number as it can be divided by 9, the sum of its digits (8+1=9). In this article, we will discuss various approaches to determine whether the given number is a Harshad Number in Python.
Example:
Input: 18 Output: 18 is a Harshad Number Input: 15 Output: 15 is not a Harshad Number
Python Program to Check If a Number is a Harshad Number
Below are some of the approaches by which we can check if a number is a Harshad Number using Python:
- Using Loop
- Using String
Using Loop
In this example, the checkHarshad
function examines whether a number is a Harshad number by verifying if the sum of its digits is divisible by the number itself. If it is, it returns “Yes”; otherwise, it returns “No”.
def checkHarshad(n):
sum = 0
temp = n
while temp > 0:
sum = sum + temp % 10
temp = temp // 10
# Return true if sum of digits is multiple of n
return n % sum == 0
if(checkHarshad(12)):
print("Yes")
else:
print("No")
if (checkHarshad(15)):
print("Yes")
else:
print("No")
Output
Yes No
Using String
In this example, we are using str() function to check if a number is a Harshad Number or not.
def checkHarshad(n):
# Converting integer to string
st = str(n)
sum = 0
length = len(st)
for i in st:
sum = sum + int(i)
# Comparing number and sum
if (n % sum == 0):
return "Yes"
else:
return "No"
number = 18
print(checkHarshad(number))
number = 15
print(checkHarshad(number))
Output
Yes No