Happy Numbers

21 Jun, 2022
A Happy Number n is defined by the following process. Starting with n, replace it with the sum of the squares of its digits, and repeat the process until n equals 1, or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are Happy Numbers, while those that do not end in 1 are unhappy numbers.First few happy numbers are 1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100Examples:  
Input :  23
Output : Yes
Explanation : 
First Iteration:
22 + 32 = 4 + 9 = 13
Second Iteration:
12 + 32 = 1 + 9 = 10
Third Iteration:
12 + 02 = 1 + 0 = 1
Since we reach 1, 23 is Happy.
 
The idea is simple, we repeated do sum of squares of digits. While doing so, we keep track of visited numbers using a hash. If we reach 1, we return true. Else if we reach a visited a number, we return false. 
C++
Java
Python 3
C#
// CPP program to check if a number// is happy number#include <bits/stdc++.h>using namespace std; // Returns sum of squares of digits// of a number n. For example for n = 12// it returns 1 + 4 = 5int sumDigitSquare(int n){    int sq = 0;    while (n) {        int digit = n % 10;        sq += digit * digit;        n = n / 10;    }    return sq;} // Returns true if n is Happy number// else returns false.bool isHappy(int n){    // A set to store numbers during    // repeated square sum process    set<int> s;    s.insert(n);     // Keep replacing n with sum of    // squares of digits until we either    // reach 1 or we endup in a cycle    while (1) {         // Number is Happy if we reach 1        if (n == 1)            return true;         // Replace n with sum of squares        // of digits        n = sumDigitSquare(n);         // If n is already visited, a cycle        // is formed, means not Happy        if (s.find(n) != s.end())            return false;         // Mark n as visited        s.insert(n);    }     return false;} // Driver codeint main(){    int n = 23;    if (isHappy(n))        cout << "Yes" << endl;    else        cout << "No" << endl;    return 0;}
// Java program to check if a number// is happy numberimport java.util.*; class GFG{ // Returns sum of squares of digits// of a number n. For example for n = 12// it returns 1 + 4 = 5static int sumDigitSquare(int n){    int sq = 0;    while (n > 0)    {        int digit = n % 10;        sq += digit * digit;        n = n / 10;    }    return sq;} // Returns true if n is Happy number// else returns false.static boolean isHappy(int n){    // A set to store numbers during    // repeated square sum process    HashSet<Integer> s = new HashSet<Integer>();    s.add(n);     // Keep replacing n with sum of    // squares of digits until we either    // reach 1 or we endup in a cycle    while (true)    {         // Number is Happy if we reach 1        if (n == 1)            return true;         // Replace n with sum of squares        // of digits        n = sumDigitSquare(n);         // If n is already visited, a cycle        // is formed, means not Happy                 if ((s.contains(n) && n != (int)s.toArray()[ s.size()-1 ] ))            return false;         // Mark n as visited        s.add(n);    }} // Driver codepublic static void main(String[] args){    int n = 23;    if (isHappy(n))        System.out.println("Yes");    else        System.out.println("No");}} /* This code contributed by PrinciRaj1992 */
# python program to check if a number# is happy number  # Returns sum of squares of digits# of a number n. For example for n = 12# it returns 1 + 4 = 5def sumDigitSquare( n):    sq = 0;    while (n!=0):        digit = n % 10        sq += digit * digit        n = n // 10             return sq;  # Returns true if n is Happy number# else returns false.def isHappy(n):    # A set to store numbers during    # repeated square sum process    s=set()    s.add(n)     # Keep replacing n with sum of    # squares of digits until we either    # reach 1 or we endup in a cycle    while (True):         # Number is Happy if we reach 1        if (n == 1):            return True;         # Replace n with sum of squares        # of digits        n = sumDigitSquare(n)         # If n is already visited, a cycle        # is formed, means not Happy        if n in s:            return False         # Mark n as visited        s.add(n)     return false;  # Driver code n = 4if (isHappy(n)):    print("Yes")else:    print("No")
// C# program to check if a number// is happy numberusing System;using System.Collections.Generic; class GFG{ // Returns sum of squares of digits// of a number n. For example for n = 12// it returns 1 + 4 = 5static int sumDigitSquare(int n){    int sq = 0;    while (n > 0)    {        int digit = n % 10;        sq += digit * digit;        n = n / 10;    }    return sq;} // Returns true if n is Happy number// else returns false.static bool isHappy(int n){    // A set to store numbers during    // repeated square sum process    HashSet<int> s = new HashSet<int>();    s.Add(n);     // Keep replacing n with sum of    // squares of digits until we either    // reach 1 or we endup in a cycle    while (true)    {         // Number is Happy if we reach 1        if (n == 1)            return true;         // Replace n with sum of squares        // of digits        n = sumDigitSquare(n);         // If n is already visited, a cycle        // is formed, means not Happy        if (s.Contains(n))            return false;         // Mark n as visited        s.Add(n);    }} // Driver codepublic static void Main(){    int n = 23;    if (isHappy(n))        Console.WriteLine("Yes");    else        Console.WriteLine("No");}} // This code contributed by Rajput-Ji
Output:  
Yes
One important observation is, the cycle always contains 4. So we don’t need to keep track of all numbers. We can simply check for 4.  
C++
C
Java
Python3
C#
PHP
Javascript
// A space optimized CPP program to check if a number is// happy number#include <bits/stdc++.h>using namespace std; // Returns sum of squares of digits of a number n.// For example for n = 12 it returns 1 + 4 = 5int sumDigitSquare(int n){    int sq = 0;    while (n) {        int digit = n % 10;        sq += digit * digit;        n = n / 10;    }    return sq;} // Returns true if n is Happy number else returns false.bool isHappy(int n){    // Keep replacing n with sum of squares of digits until    // we either reach 1 or we end up in a cycle    while (1) {        // Number is Happy if we reach 1        if (n == 1)            return true;        // Replace n with sum of squares of digits        n = sumDigitSquare(n);        // Number is not Happy if we reach 4        if (n == 4)            return false;    }    return false;} // Driver codeint main(){    int n = 23;    if (isHappy(n))        cout << "Yes" << endl;    else        cout << "No" << endl;    return 0;} // This code is contributed by Sania Kumari Gupta (kriSania804)
// A space optimized C program to check if a number is happy// number#include <stdbool.h>#include <stdio.h> // Returns sum of squares of digits of a number n.// For example for n = 12 it returns 1 + 4 = 5int sumDigitSquare(int n){    int sq = 0;    while (n) {        int digit = n % 10;        sq += digit * digit;        n = n / 10;    }    return sq;} // Returns true if n is Happy number else returns false.bool isHappy(int n){    // Keep replacing n with sum of squares of digits until    // we either reach 1 or we end up in a cycle    while (1) {        // Number is Happy if we reach 1        if (n == 1)            return true;        // Replace n with sum of squares of digits        n = sumDigitSquare(n);        // Number is not Happy if we reach 4        if (n == 4)            return false;    }    return false;} // Driver codeint main(){    int n = 23;    if (isHappy(n))        printf("Yes\n");    else        printf("No\n");    return 0;} // This code is contributed by Sania Kumari Gupta (kriSania804)
// A space optimized Java// program to check if a// number is happy numberimport java.io.*; class GFG {         // Returns sum of squares of    // digits of a number n. For    // example for n = 12 it    // returns 1 + 4 = 5    static int sumDigitSquare(int n)    {        int sq = 0;        while (n != 0)        {            int digit = n % 10;            sq += digit * digit;            n = n / 10;        }        return sq;    }         // Returns true if n is Happy    // number else returns false.    static boolean isHappy(int n)    {        // Keep replacing n with        // sum of squares of digits        // until we either reach 1        // or we end up in a cycle        while (true)        {                 // Number is Happy if            // we reach 1            if (n == 1)                return true;                 // Replace n with sum            // of squares of digits            n = sumDigitSquare(n);                 // Number is not Happy            // if we reach 4            if (n == 4)                return false;        }         }         // Driver code    public static void main(String args[])    {        int n = 23;        if (isHappy(n))            System.out.println("Yes");        else            System.out.println("No" );    }} /*This code is contributed by Nikita tiwari.*/
# A space optimized Python3 program to# check  if a number is happy number  # Returns sum of squares of# digits of a number n. For# example for n = 12 it# returns 1 + 4 = 5def sumDigitSquare(n) :    sq = 0    while (n) :        digit = n % 10        sq = sq + digit * digit        n = n // 10         return sq  # Returns true if n# is Happy number else# returns false.def isHappy(n) :     # Keep replacing n with    # sum of squares of digits    # until we either reach 1    # or we end up in a cycle    while (1) :         # Number is Happy if        # we reach 1        if (n == 1) :            return True         # Replace n with sum of        # squares of digits        n = sumDigitSquare(n)         # Number is not Happy        # if we reach 4        if (n == 4) :            return False         return False # Driver coden = 23if (isHappy(n)) :    print("Yes")else :    print("No")      # This code is contributed# by Nikita tiwari.
// A space optimized C#// program to check if a// number is happy numberusing System; class GFG{     // Returns sum of squares of// digits of a number n. For// example for n = 12 it// returns 1 + 4 = 5static int sumDigitSquare(int n){    int sq = 0;    while (n != 0)    {        int digit = n % 10;        sq += digit * digit;        n = n / 10;    }    return sq;} // Returns true if n is Happy// number else returns false.static bool isHappy(int n){    // Keep replacing n with    // sum of squares of digits    // until we either reach 1    // or we end up in a cycle    while (true)    {         // Number is Happy if        // we reach 1        if (n == 1)            return true;         // Replace n with sum        // of squares of digits        n = sumDigitSquare(n);         // Number is not Happy        // if we reach 4        if (n == 4)            return false;    } } // Driver codestatic public void Main (){    int n = 23;    if (isHappy(n))        Console.WriteLine("Yes");    else        Console.WriteLine("No" );}} // This code is contributed by ajit
<?php// A space optimized PHP// program to check if a// number is happy number // Returns sum of squares// of digits of a number// n. For example for n = 12// it returns 1 + 4 = 5function sumDigitSquare($n){    $sq = 0;    while ($n)    {        $digit = $n % 10;        $sq += $digit * $digit;        $n = $n / 10;    }    return $sq;} // Returns true if n// is Happy number// else returns false.function isHappy($n){    // Keep replacing n with    // sum of squares of digits    // until we either reach 1    // or we end up in a cycle    while (1)    {         // Number is Happy        // if we reach 1        if ($n == 1)            return true;         // Replace n with sum        // of squares of digits        $n = sumDigitSquare($n);         // Number is not Happy        // if we reach 4        if ($n == 4)            return false;    }     return false;} // Driver code$n = 23;if (isHappy($n))    echo "Yes";else    echo "No"; // This code is contributed by mits?>
<script>     // A space optimized Javascript    // program to check if a    // number is happy number         // Returns sum of squares of    // digits of a number n. For    // example for n = 12 it    // returns 1 + 4 = 5    function sumDigitSquare(n)    {        let sq = 0;        while (n != 0)        {            let digit = n % 10;            sq += digit * digit;            n = parseInt(n / 10, 10);        }        return sq;    }     // Returns true if n is Happy    // number else returns false.    function isHappy(n)    {        // Keep replacing n with        // sum of squares of digits        // until we either reach 1        // or we end up in a cycle        while (true)        {             // Number is Happy if            // we reach 1            if (n == 1)                return true;             // Replace n with sum            // of squares of digits            n = sumDigitSquare(n);             // Number is not Happy            // if we reach 4            if (n == 4)                return false;        }     }         let n = 23;    if (isHappy(n))        document.write("Yes");    else        document.write("No" ); </script>
Output:  
Yes
Time complexity: O(log N) where N is no of digits of a given number n
Auxiliary Space : O(1)This article is contributed by ashish madaan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
jit_t
Mithun Kumar
princiraj1992
Rajput-Ji
Atul_kumar_Shrivastava
decode2207
krisania804
polymatir3j
number-theory
series
Mathematical
number-theory
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.