- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Happy Numbers in Python
Suppose we have a number n. We shall check whether it is one Happy number or not. As we know, the happy number is a number, where starting with any positive integers replace the number by the sum of squares of its digits, this process will be repeated until it becomes 1, otherwise it will loop endlessly in a cycle. Those numbers, when the 1 has found, they will be happy number.
So, the input is like 19, the output will be true as the number is happy number. As we can see from 19, we will get
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
To solve this, we will follow these steps −
- Here we will use the dynamic programming approach, and solve this using recursion
- Base case is, when n = 1, then return true
- When n is already visited, return false
- mark n as visited
- n := n as string, l := list of all digits in n
- temp := squared sum of all digits
- return function recursively with parameter temp and visited list
Let us see the following implementation to get better understanding −
Example
class Solution(object): def isHappy(self, n): return self.solve(n,{}) def solve(self,n,visited): if n == 1: return True if n in visited: return False visited[n]= 1 n = str(n) l = list(n) l = list(map(int,l)) temp = 0 for i in l: temp += (i**2) return self.solve(temp,visited) ob = Solution() print(ob.isHappy(19))
Input
19
Output
True
- Related Articles
- Happy Number in Python
- Determining happy numbers using recursion JavaScript
- Python program to print all Happy numbers between 1 and 100
- The Happy Prince
- Longest Happy Prefix in C++
- Longest Happy String in C++
- Python program to check if the given number is Happy Number
- Program to find maximum number of people we can make happy in Python
- C++ program to print Happy Birthday
- Write a program for Happy Woman’s Day in c++
- How can I be happy in life at all times?
- Random numbers in Python
- Complex Numbers in Python?
- Big Numbers in Python
- Add Two Numbers in Python

Advertisements