- Related Questions & Answers
- Python program to check if the given number is a Disarium Number
- Python program to check if a given string is number Palindrome
- Python Program for How to check if a given number is a Fibonacci number?
- How to check if a given number is a Fibonacci number in Python Program ?
- Check if the given number is Ore number or not in Python
- Java Program for check if a given number is Fibonacci number?
- Check if given number is Emirp Number or not in Python
- Python Program to Check if a Number is a Strong Number
- Python Program to Check if a Number is a Perfect Number
- Check if given number is perfect square in Python
- Happy Number in Python
- Java program to check whether the given number is an Armstrong number
- Program to check whether given number is Narcissistic number or not in Python
- C program to find if the given number is perfect number or not
- Check if a given string is a valid number in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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");

The number is being checked 86 is a happy number

- 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.

Advertisements