A Harshad number (or a Niven number) is a number that is evenly divisible by the sum of its digits. An example is 18 (1+8=9, 18%9 = 0). Write a function called isHarshad(num) that takes an integer as an argument and returns True if the number is a Harshad number and False if it is not. Then, use this function to create a list of all of the Harshad numbers in the first 500 natural numbers.
Python code pasted below.
#function definition
def isHarshad(num):
#initialize sum to 0
sum=0
#convert num to string
s=str(num)
#Take each digit from the string
for i in range(len(s)):
#convert each digit to integer and find the sum.
sum=sum+int(s[i])
#If Harshad number return true else retun false
if num%sum==0:
return True
else:
return False
#main program
#Generate a list of all harshad numbers in first 500 natural
numbers
#initalize an empty list
harshad=[]
for i in range(1,501):
if(isHarshad(i)):
harshad.append(i)
print("List of all harshad numbers in first 500 natural numbers is
",harshad)
Python code in IDLE pasted for better understanding of the indent.
Output screen
Get Answers For Free
Most questions answered within 1 hours.