Happy Number in JAVA
Happy Number
Happy Number: A Happy Number is defined as : Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1.
Example :-
Input : 49
Output : It is a Happy Number
Input : 4
Output : It is not a Happy Number
Algorithm, Program and Video Link given below :-
Algorithm :-
• Input number
• Store the input number in another variable
• Use a infinite for loop
• Inside for loop use While loop to store the sum of square of the digits in a variable
• Check if the number is equal to original number or a particular number repeating after looping.
• If the number is repeating or it is equal to the Input number print “Number is not a Happy Number”
• Otherwise check if the number is equal to 1. If it is equal to 1 then print “It is a Happy Number”
• Else find the sum of the square of the digits again.
• Repeat the process until a desired result is obtained.
• Compile and Run the Program.
Program :-
import java.io.*;
import java.util.*;
class Happy_Number
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int n,p,i,j,k=0,rev,s=0,x;
int ar[]= new int[100];
System.out.println("Enter Number");
n= in.nextInt();// Enter number from user
p=n; // Store the copy of input number
for(i=0;;i++)
{
while(n>0)
{
rev=n%10;
s=s+(rev*rev);
n=n/10;
ar[i]=s;
}
for(j=0;j<i;j++)
{
if(ar[j]==ar[i])
{
for(x=0;x<=i;x++)
{
System.out.print(ar[x]+"\t");
}
System.out.println();
System.out.println("It is not a Happy Number : "+p);
k=1;
break;
}
}
if(k==1)
{
break;
}
else if(s==1)
{
for(x=0;x<=i;x++)
{
System.out.print(ar[x]+"\t");
}
System.out.println();
System.out.println("It is a Happy Number : "+p);
break;
}
else
{
n=s;
s=0;
}
} // end of for loop
} // end of main
} // end of class
import java.util.*;
class Happy_Number
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int n,p,i,j,k=0,rev,s=0,x;
int ar[]= new int[100];
System.out.println("Enter Number");
n= in.nextInt();// Enter number from user
p=n; // Store the copy of input number
for(i=0;;i++)
{
while(n>0)
{
rev=n%10;
s=s+(rev*rev);
n=n/10;
ar[i]=s;
}
for(j=0;j<i;j++)
{
if(ar[j]==ar[i])
{
for(x=0;x<=i;x++)
{
System.out.print(ar[x]+"\t");
}
System.out.println();
System.out.println("It is not a Happy Number : "+p);
k=1;
break;
}
}
if(k==1)
{
break;
}
else if(s==1)
{
for(x=0;x<=i;x++)
{
System.out.print(ar[x]+"\t");
}
System.out.println();
System.out.println("It is a Happy Number : "+p);
break;
}
else
{
n=s;
s=0;
}
} // end of for loop
} // end of main
} // end of class
Output :-
Output |
Video Link : https://youtu.be/NNDL-PvRaZ0
Follow me on Instagram
All the Best :)
Keep Learning :)
Comments
Post a Comment