In this simple python program, we have to check for a Harshad number. It's a number python program.
To understand this example, you should have knowledge of the following Python programming topics:
A Harshad number is a number in which the sum of the digits in that number must be a divisor of that number. Which means the given number must be divisible by the sum of the digits of the number.
For example,
In this simple python program, we use a while loop
until the number is greater than zero. Then get the digit from the number using the mod (%) operator, and we add the digit to get the sum. Now divide the number by 10 to split the number and remove one digit. Then we again use the Mod operator to check the number is divisible by sum using the if condition statement in python. If its remainder is zero, then print its Harshad number.
STEP 1: Initialize a number with some predefined number.
STEP 2: Initialize the reminder and sum it to zero.
STEP 3: Copy the number to another variable to save its value.
STEP 4: Use a while loop
until the number is greater than zero.
STEP 5: Calculate the remainder using the mod operator, and we get the digits of the number.
STEP 6: Add the sum as a sum and reminder, and split the number by dividing the number by 10 to remove one digit from the number.
STEP 7: Using an if
condition, check the number mod sum is equal to zero.
STEP 8: If it is zero, print it's a Harshad number. Else
print, not Harshad, using the python programming language.
num = 54;
rem = sum = 0;
n = num;
while(num > 0):
rem = num
sum = sum + rem; # calculating the sum of digits of the number
num = num//10;
if(n%sum == 0):
print(str(n) + " is a harshad number");
else:
print(str(n) + " is not a harshad number");
54 is a harshad number