Python program to print all Happy numbers between 1 and 100

PythonServer Side ProgrammingProgramming

When it is required to print all the ahppy numbers between 1 and 100, a simple loop and operations like ‘%’, ‘+’, and ‘//’ are used.

A happy number is the one that ends up as 1, when it is replaced by the sum of square of every digit in the number.

To print the happy numbers between a given range, a simple loop can be used.

Below is a demonstration for the same −

Example

 Live Demo

def check_happy_num(my_num):
   remaining = sum_val = 0
   while(my_num > 0):
      remaining = my_num%10
      sum_val = sum_val + (remaining*remaining)
      my_num = my_num//10
   return sum_val
print("The list of happy numbers between 1 and 100 are : ")
for i in range(1, 101):
   my_result = i
   while(my_result != 1 and my_result != 4):
      my_result = check_happy_num(my_result)
   if(my_result == 1):
      print(i)

Output

The list of happy numbers between 1 and 100 are :
1
7
10
13
19
23
28
31
32
44
49
68
70
79
82
86
91
94
97
100

Explanation

  • A method named ‘check_happy_num’ is defined, that takes a number as parameter.
  • It checks to see if the number is greater than 0.
  • A sum variable is assigned to 0.
  • It divides the number by 10 and gets the remainder, and assigns it to a value.
  • This remainder is multipled with itself and added to a ‘sum’ variable.
  • This occurs on all digits of the number.
  • This sum is returned as output.
  • A range is defined, 1 to 101, and the numbers are iterated over.
  • Every number is called on the previously defined method.
  • If it is a happy number, it is displayed on the console.
raja
Published on 12-Mar-2021 12:13:00
Advertisements