Checking Whether the Number is Harshad or not using Python

Harshad Number

Harshad number in a given base is an integer that is divisible by the sum of the digits when written in that base. Harshad numbers in base n are also known as n-harshad numbers. Below are first few harshad numbers in base 10 are 1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27………………….In this program we will be checking whether the given number is harshad number or not.

  • Example : n=408,
    • sum of digits of 408 = 12
    • 408 is divisible by 12
    • 408 is Harshad number
Finding Harshad Number using Python

Algorithm

  • Input number
  • Extracting the digits of the number using % operation and summing them
  • Checking whether the number is divisible by the sum
  • If divisible print “Harshad number”
  • else print “Not Harshad number”

Python Code

General Solution:

n=int(input(“Enter any number”))
p=n
l=[]
sum1=0
while(n>0):
    x=n%10
    l.append(x)
    n=n//10
sum1=sum(l)
if(p%sum1==0):
    print(“Harshad number”)
else:
    print(“Not harshad number”)

 

Optimal solution:

n=int(input(“Enter any number”))
p=n
sum1=0
while(n>0):
    sum1+=n%10
    n=n//10
if(p%sum1==0):
    print(“Harshad number”)
else:
    print(“Not harshad number”)


Output

Enter any number 170
Not harshad number