write a program to check whether the number is happy or not in java
Answers
Happy Numbers
Happy numbers are special numbers with a special property. We define a process as follows:
- Take a number N
- Replace the number N by the sum of squares of its digits
- Keep repeating the process until either it equals 1 or it runs into an infinite loop never equalling 1
If the process ends with 1, then the original number N is called a Happy Number.
Let us take an example:
-> N = 7
Thus, 7 is a Happy Number.
-> N = 8
Note that we encountered 89 again. Both steps are highlighted in bold. We see that we are going to run into an infinite loop.
So, 8 is not a Happy Number.
So, if we are to write a program, what conditions do we keep so as to recognize when we are going into an infinite loop?
There can be many logics. The one I am going to show uses a special property of non-happy Numbers:
All non-happy numbers reach the cycle: 4, 16, 37, 58, 89, 145, 42, 20, 4, ...
So we can design a code, as follows:
/* A happy number is defined as follows:
* Start with any positive integer, replace the number by the sum of the squares of its digits,
* and repeat the process until the number either equals 1 (where it will stay),
* or it loops endlessly in a cycle which does not include 1.
*/
import java.util.*;
class HappyNumber {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int N=sc.nextInt(); //Taking User Input
if(N>0){
boolean isHappy=false; //Setting isHappy to false
int s=sq(N); //Taking s as sum of squares of digits of N
while(s!=4){ //If s equals 4 at any point, then N is not a Happy Number
if(s==1){
isHappy=true;
break;
}
s=sq(s); //Taking sum of squares of digits again
}
if(isHappy){
System.out.println(N+" is a Happy Number.");
}
else{
System.out.println(N+" is not a Happy Number.");
}
}
else //Program can only run for inputs of Natural Numbers. So invalid input case added.
{
System.out.println("Invalid input. Please enter only natural numbers.");
}
}
static int sq(int n){ //Function to calculate sum of squares of digits of a number n
int s=0; //s will contain the answer
while(n!=0){
int d=n%10; //Extracting each digit
s+=d*d; //Adding the square of the digit to s
n=n/10; //Reducing value of n by taking quotient of division by 10
}
return s;
}
}
import java.util.*;
class happy_number
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number to check whether it is happy number or not");
int n=sc.nextInt();
int s=n;
int d=0;
while(s>9)
{
n=s;
s=0;
while(n>0)
{
d=n%10;
s=s+(d*d);
n=n/10;
}
}
if(s==1)
{
System.out.println("Happy number");
}
else
{
System.out.println("Not a happy number");
}
}
}