Check If A Number Is A Harshad Number or Not in Python
In this tutorial, we will be looking at a program in Python that will check if a number is a harshad number or not. We will be using the following Python concepts:
- Python if…else Statement
- Loops in Python
A number is called a harshad number if the number is divisible by the sum of its digits. Harshad numbers are also known as Niven numbers. For example:
156 is divisible by the sum of its digits, i.e. 1 + 5 + 6 = 12
num = int(input("Enter a number: ")) digit = sum = 0 temp = num # Calculates sum of digits while(temp > 0): digit = temp % 10 sum = sum + digit temp = temp // 10 # Checks whether the number is divisible by the sum of digits if num % sum == 0: print(num, "is a Harshad Number!!!") else: print(num, "is not a Harshad Number!!!")
First, we ask the user to input the number using int(input(“Enter a number: “)). In our code, the input() prints our message on the console and also reads the input given as a string. But we want the input to be an integer so that we can perform mathematical operations on them. For this reason, we use the int() function.
We then initiate temp as the num we just read. We also initiate both sum and digit as 0, this also signifies that they are of int type.
Then we start a while loop to find the digits of temp using mod(%). We then find the sum of each of these digits by adding it to sum. This loop continues till temp becomes equals to 0. At this point we exit the loop.
Now we use an if…else statement to check if num is divisible by sum or not. If it is then num is a harshad number and we print this. If not then we display that num is not a harshad number.
Enter number: 156 156 is a Harshad Number!!! Enter number: 67 67 is not a Harshad Number!!!
So here it is a simple program to check if a number is a Harshad Number or not.