Program to print Happy Numbers between 1 and 100 in Python. This program contains if else condition statement, for, while loop and print statement. This is for beginners, class 11,12 and B Tech computer science students.
Program to print Happy Numbers between 1 and 100 in Python
What is Happy numbers ?
In number theory, a Happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. For instance, 13 is a happy number because , and
. On the other hand, 4 is not a happy number because the sequence starting with
and
eventually reaches
, the number that started the sequence, and so the process continues in an infinite cycle without ever reaching 1. A number which is not happy is called sad or unhappy.
Source code :
def isHappyNumber(num):
rem = sum = 0;
while(num > 0):
rem = num%10;
sum = sum + (rem*rem);
num = num//10;
return sum;
print("List of happy numbers between 1 and 100: ");
for i in range(1, 101):
result = i;
while(result != 1 and result != 4):
result = isHappyNumber(result);
if(result == 1):
print(i),
print(" "),
Source code Explanation :
Step 1: isHappyNumber() function will determine whether a number is happy or not
def isHappyNumber(num):
rem = sum = 0;
Step 2: Calculates the sum of squares of digits using while loop
while(num > 0):
rem = num%10;
sum = sum + (rem*rem);
num = num//10;
return sum;
Step 3:Displays all happy numbers between 1 and 100
print(“List of happy numbers between 1 and 100: “);
for i in range(1, 101):
result = i;
Step 4:Happy number always ends with 1 and unhappy number ends in a cycle of repeating numbers which contains 4
while(result != 1 and result != 4):
result = isHappyNumber(result);
if(result == 1):
print(i),
print(” “),
Output :
List of happy numbers between 1 and 100: 1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100
Output Explanation :
The List of happy number between 1 and 100 is printed on the screen.
Conclusion :
The program runs fine.
Thank you for reading, learning and download source code of Program to print Happy Numbers between 1 and 100 in Python. This program contains if else condition statement, for, while loop and print statement. This is for beginners, class 11,12 and B Tech computer science students. for more programs links is given below-
Python Programs Archives – CS Study
Computer Science with Python Practical Book Solutions Class 11 Term -2 – CS Study
Computer Science Practical file for class 12 Term-2 – CS Study