Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Happy Number?
3.
What is a Happy Number in Java?
3.1.
The Logic Behind Happy Numbers in Java
4.
Problem Statement
4.1.
Algorithm
4.2.
Java Implementation
4.3.
Implementation in Python
4.4.
Implementation in C
4.5.
Implementation in C#
4.6.
Implementation in PHP#
5.
Frequently Asked Questions
5.1.
How to check if a number is happy Java?
5.2.
How do you work out a happy number?
5.3.
What is the range of happy numbers in Java?
5.4.
Are there an infinite number of happy numbers?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Happy Number in Java

Author Sanjana Yadav
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Hello Reader!!

Doesn't the name “Happy number” itself make you curious about Happy numbers? What are these numbers? How do we know if a given number is a happy number? We will find answers to all these questions today.

In this article, we will learn about Happy numbers in Java and write a program to check whether a number entered is a Happy number.

Happy Number in Java

So, let’s get started!

What is a Happy Number?

A happy number is a number that yields 1 when substituted by the sum of its digits, squared repeatedly. If this method produces an infinite cycle of numbers containing 4, the number is known as an unhappy number. We will look at the implementation of finding out whether a number is a happy number in java. 

For example, 49 is a happy number since the procedure results in 1, as seen below.

49→ 4^2 + 9^2=97
97→ 9^2 + 7^2=130
130→1^2 + 3^2+0^2=10
10→ 1^2 + 0^2=1

More examples of happy numbers are 7, 28, 32, 100, 320, etc.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is a Happy Number in Java?

A digit is called happy if the sum of the square of the digit gives 1 after the sequence of steps, and in each step, the number is replaced by the previous sum of the square. Let's understand it with an example:
13-> 1^2 + 3^2 = 10
10-> 1^2 + 0^2 = 1
Above, we see that the number eventually gives us 1 as the output, and hence the number 13 is a happy number.

The Logic Behind Happy Numbers in Java

Example

Problem Statement

Write a Program to determine whether a given number N is a happy number in Java.

Algorithm

Below is the algorithm to determine whether a number is a happy number or not. Follow the steps below:

  1. Take the number to be tested from the keyboard and store it in some variable, say num.
  2. Pass this variable to a function called isNumHappy(), which returns the final sum value.
  3. Inside the function, 
    1. Divide(%) num by ten and store the remainder in another variable, say rem.
    2. Declare a variable sum(initialize with 0) and add the square of rem to it.
    3. Now, divide(/) the num by 10.
    4. Repeat steps 2–4 until we get the sum of the squares of all the digits in the given number num.
    5. The final addition value is then stored in the variable sum.
    6. Return sum.
  4. Create a variable named finalVal and initialize it with num.
  5. If finalVal is not equal to 1 and 4, then simply call the isNumHappy() function by passing the finalVal as a parameter and storing the result in finalVal itself.
  6. If finalVal’s value becomes 1, print “The number entered is a Happy number”; else, print “The number entered is not a Happy number.”

Java Implementation

Below is the implementation to find happy number in java.

import java.util.*;

public class HappyNum {
    public static int isNumHappy(int num) {
        int rem = 0, sum = 0;
        // calculate the sum of squares of each digit
        while (num > 0) {
            rem = num % 10;
            sum = sum + (rem * rem);
            num = num / 10;
        }
        return sum;
    }
    
    public static void main(String[] args) {
        // Take num
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number greater than 0:");
        int num = sc.nextInt();
        int finalVal = num;
        while (finalVal != 1 && finalVal != 4) {
            finalVal = isNumHappy(finalVal);
        }
        if (finalVal == 1) {
            System.out.println("The number entered is a Happy Number");
        } else {
            System.out.println(" The number entered is not a Happy Number");
        }
    }
}


Output

Enter a number greater than 0:15
The number entered is not a Happy Number

Enter a number greater than 0: 10
10
The number entered is a Happy Number


Time complexity

O(log N). Here, N represents the number of digits in the given number num.

Space Complexity

O(1), as no extra space is needed.

Implementation in Python

def check_happy_number(i):
 check = set()
 while i != 1:
       i = sum(int(j)**2 for j in str(i))
       if i in check:
           return False
       check.add(i)
 return True
print(check_happy_number(7))
print(check_happy_number(932))
print(check_happy_number(6))


Output

True
True
False

Implementation in C

#include <stdio.h>  
int check_happy_number(int num){  
    int rem = 0, sum = 0;  
    while(num > 0){  
        rem = num%10;  
        sum = sum + (rem*rem);  
        num = num/10;  
    }  
    return sum;  
}  
      
int main()  
{  
    int num = 13;  
    int result = num;  
      
    while(result != 1 && result != 4){  
        result = check_happy_number(result);  
    }  
    if(result == 1)  
        printf("%d is a happy number", num);  
    else if(result == 4)  
        printf("%d not is a happy number", num);   
   
    return 0;  
}  


Output

13 is a happy number

Implementation in C#

using System;                    
public class Happy_Number  
{  
   public static int check_happy_number(int num){  
       int rem = 0, sum = 0;  
       while(num > 0){  
           rem = num%10;  
           sum = sum + (rem*rem);  
           num = num/10;  
       }  
       return sum;  
   }  
     
   public static void Main()  
   {  
       int num = 13;  
       int result = num;  
         
       while(result != 1 && result != 4){  
           result = check_happy_number(result);  
       }  
       if(result == 1)  
           Console.WriteLine(num + " : is a happy number");  
       else if(result == 4)  
           Console.WriteLine(num + " : is not a happy number");    
   }  
}  


Output

13 is a happy number

Implementation in PHP#

<?php 
function check_happy_number($num){  
  $rem = $sum = 0; 
  while($num > 0){  
      $rem = $num%10;  
      $sum = $sum + ($rem*$rem);  
      $num = intval($num/10);  
  }  
  return $sum;  
}  
 
$num = 13;  
$result = $num;  
 
while($result != 1 && $result != 4){  
  $result = check_happy_number($result);  
}  
 
if($result == 1)  
  print($num . " : is a happy number"); 
else if($result == 4)  
  print($num . " : is not a happy number");     
?>


Output

13 is a happy number

Frequently Asked Questions

How to check if a number is happy Java?

To check if a number is happy in Java, first, calculate the sum of the squares of its digits. If the result is 1, the number is happy. If not, repeat the process until either 1 is reached or the same sum is repeated.

How do you work out a happy number?

The logic of a happy number is to repeatedly sum the squares of its digits until the result is either 1 or a previously obtained sum. If the result is 1, the number is happy. If not, it is an unhappy number.

What is the range of happy numbers in Java?

The range of happy numbers is not defined as such mostly it depends upon the input values. A happy number is a number that yields 1 when substituted by the sum of its digits, squared repeatedly.

Are there an infinite number of happy numbers?

Right now it is not proven that there are infinite numbers of happy numbers and there is a hypothesis that all numbers eventually end up in a cycle that includes either 4 or 1, with 1 being the happy number in it.

Conclusion

In this article, we learned about Happy numbers in Java. We also implemented a Java code to check whether a given number is Happy or not.

We hope this article has clarified your understanding of Happy number in Java. You can refer to our blogs to understand more about Java concepts.

 

You can also visit our website to read more such blogs. Make sure you enroll in our courses, take mock tests, solve problems, and interview puzzles. Also, you can prepare for interviews with interview experiences and an interview bundle.

Keep learning and keep growing, Ninjas!

Thank you
Live masterclass