Python program to check if the given number is Happy Number
Last Updated :
15 Apr, 2024
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.
Python3
# Function to return the sum of squares of digits of n
def numSquareSum(n):
squareSum = 0
while (n != 0):
squareSum += (n % 10) * (n % 10)
n = n // 10
return squareSum
# Function to return true if n is a Happy Number
def isHappyNumber(n):
st = set()
while (1):
n = numSquareSum(n)
if (n == 1):
return True
if n in st:
return False
st.add(n)
# Example usage:
print(isHappyNumber(20))
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.
Python3
# Utility method to return
# sum of square of digit of n
def numSquareSum(n):
squareSum = 0;
while(n):
squareSum += (n % 10) * (n % 10);
n = int(n / 10);
return squareSum;
# method return true if
# n is Happy number
def isHappynumber(n):
# initialize slow
# and fast by n
slow = n;
fast = n;
while(True):
# move slow number
# by one iteration
slow = numSquareSum(slow);
# move fast number
# by two iteration
fast = numSquareSum(numSquareSum(fast));
if(slow != fast):
continue;
else:
break;
# if both number meet at 1,
# then return true
return (slow == 1);
# Driver Code
n = 13;
if (isHappynumber(n)):
print(n , "is a Happy number");
else:
print(n , "is not a Happy number");
Output13 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.
Python3
# Method - returns true if the input is
# a happy number else returns false
def isHappynumber(n):
if n == 1 or n == 7:
return True
Sum, x = n, n
# This loop executes till the sum
# of square of digits obtained is
# not a single digit number
while Sum > 9:
Sum = 0
# This loop finds the sum of
# square of digits
while x > 0:
d = x % 10
Sum += d * d
x = int(x / 10)
if Sum == 1:
return True
x = Sum
if Sum == 7:
return True
return False
n = 13
if isHappynumber(n):
print(n, "is a Happy number")
else:
print(n, "is not a Happy number")
Output13 is a Happy number
Time Complexity: O(n*log(n)).
Auxiliary Space: O(1).
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read