Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to Check Number is a Power of Two
Next article icon

Python program to check if the given number is Happy Number

Last Updated : 15 Apr, 2024
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.

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

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.

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

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.

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

Output
13 is a Happy number 

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


Next Article
Python Program to Check Number is a Power of Two
author
ravi_sadam
Improve
Article Tags :
  • Python
  • Python Programs
  • Python-DSA
Practice Tags :
  • python

Similar Reads

  • Python Program to Check If a Number is a Harshad Number
    Harshad Numbers can be divided by the sum of its digits. They are also called Niven Numbers. For instance, 18 is a Harshad Number as it can be divided by 9, the sum of its digits (8+1=9). In this article, we will discuss various approaches to determine whether the given number is a Harshad Number in
    2 min read
  • Python Program to Check if a Number is Odd or Even
    Even Numbers are exactly divisible by 2 and Odd Numbers are not exactly divisible by 2. We can use modulo operator (%) to check if the number is even or odd. For even numbers, the remainder when divided by 2 is 0, and for odd numbers, the remainder is 1. In this article, we will learn how to check i
    2 min read
  • How to Check if a Given Number is Fibonacci number - Python
    Fibonacci numbers are part of a famous sequence where each number is the sum of the two preceding ones, i.e. F(n) = F(n-1) + F(n-2). The sequence starts as: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... Notice that every number is equal to the sum of its previous 2 numbers. In this article, we will learn how
    2 min read
  • Python Program to Check Number is a Power of Two
    we will discuss how to write a Python program to determine whether a given number is a power of two. A number is said to be a power of two if it can be expressed in the form of 2n, where n is a non-negative integer. Examples: [GFGTABS] Python def is_power_of_two(n): if n <= 0: return False return
    4 min read
  • Python Program to Find Numbers Divisible by Another Number
    We are given a list of numbers and a number. We have to find all the numbers in the list that are divisible by the given single number. Examples: Input: list=[8, 14, 21, 36, 43], num=3Output: 21, 36, 57Input: list=[2, 17, 25, 31, 48, 55], num=5Output: 25, 55In this article, we will discuss the diffe
    3 min read
  • Python program to check if the given string is IPv4 or IPv6 or Invalid
    Given a string. The task is to check if the given string is IPv4 or IPv6 or Invalid. Examples: Input : "192.168.0.1" Output : IPv4 Explanation : It is a valid IPv4 address Input : "2001:0db8:85a3:0000:0000:8a2e:0370:7334" Output : IPv6 Explanation : It is a valid IPv6 address Input : "255.32.555.5"
    1 min read
  • Check if a Number is a Whole Number in Python
    Floating-point numbers in Python can sometimes pose challenges when you need to determine whether they represent whole numbers. Due to the inherent precision limitations of floating-point representation, comparing them directly for equality with integers may lead to unexpected results. In this artic
    3 min read
  • Python program to check if number is palindrome (one-liner)
    In this article, we are given a number and we have to check whether the number is palindrome or not in one-liner code. The output will be True if it's a Palindrome number otherwise it would be False. Let's discuss how to find whether a number is palindrome or not in this article. Input1: test_number
    3 min read
  • Python program to print even numbers in a list
    Getting even numbers from a list in Python allows you to filter out all numbers that are divisible by 2. For example, given the list a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], you might want to extract the even numbers [2, 4, 6, 8, 10]. There are various efficient methods to extract even numbers from a li
    3 min read
  • Python Program for Check if all digits of a number divide it
    Given a number n, find whether all digits of n divide it or not. Examples: Input : 128Output : Yes128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Input : 130Output : No We want to test whether each digit is non-zero and divides the number. For example, with 128, we want to test d != 0 && 128 %
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences