Open In App

Python program to check if the given number is Happy Number

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A number is called happy if it leads to 1 after a sequence of steps wherein each step number is replaced by the sum of squares of its digit that is if we start with a Happy Number and keep replacing it with digits square sum, we reach 1. In this article, we will check if the given number is a Happy Number

Examples

Input: n = 19
Output: True
19 is Happy Number,

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
As we reached to 1, 19 is a Happy Number.

Input: n = 20
Output: False

Python Program to Check if Given Number is Happy Number

Below are the example of Python program to check if the given number is Happy Number.

  • Using Set() Method
  • Using No Extra Space
  • Using Extra Space.

Check if Given Number is Happy Number Using Set Method

In this example, below code defines two functions: numSquareSum calculates the sum of squares of digits of a number, and isHappyNumber checks if a number is a Happy Number, using a set to detect cycles. The example usage demonstrates checking if the number 20 is a Happy Number, which returns False.


Output
False

Time Complexity: O(n*log(n)).
Auxiliary Space: O(n) since we are using set.

Check if Given Number is Happy Number Using No Extra Space

In this example, we have a method named numSquareSum which calculates the sum of the squares of the digits of a given number. The isHappynumber method determines whether a number is a "happy number" or not. It employs two pointers, slow and fast, to iterate through the sum of squares until they either meet or reach 1, indicating a happy number.


Output
13 is a Happy number

Time Complexity: O(n*log(n)).
Auxiliary Space: O(1). 

Check if Given Number is Happy Number Using Extra Space.

In this example, below code defines a method isHappynumber to check if a given number is a "happy number". It first checks if the number is 1 or 7, which are happy numbers, and returns True. Otherwise, it iterates through the sum of squares of digits until it either reaches 1 or 7, or enters a cycle. If it reaches 1 or 7, it returns True; otherwise, it returns False.


Output
13 is a Happy number

Time Complexity: O(n*log(n)).
Auxiliary Space: O(1). 


Practice Tags :

Similar Reads