Computer >> Computer tutorials >  >> Programming >> Python

Python program to check if the given number is Happy Number


When it is required to check if a given number is a happy number, the ‘%’ operator, the ‘//’ operator and the ‘+’ operator can be 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.

Below is a demonstration for the same −

Example

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;
my_num = 86
my_result = my_num
while(my_result != 1 and my_result != 4):
   my_result = check_happy_num(my_result);
print("The number is being checked")
if(my_result == 1):
   print(str(my_num) + " is a happy number");
elif(my_result == 4):
   print(str(my_num) + " isn't a happy number");

Output

The number is being checked
86 is a happy number

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.
  • The number is defined, and a copy of it is made.
  • It is checked to see if it is a happy number by calling the function previously defined.
  • Relevant message is displayed on the console.