Happy number is similar to magic number, but instead of obtaining sum of the digits we obtain sum of square of the digits.
EXAMPLE-1
19 =1²+9²=82
82=8²+2²=68
68=6²+8²=100
100=1²+0²+0²=1
EXAMPLE-2
7=7²=49
49=4²+9²=97
97=9²+7²=130
130=1²+3²+0²=10
10=1²+0²=1
EXAMPLE-3
13=1²+3²=10
10=1²+0²=1
A java program on happy number can be made by extracting digits of the number then adding the square of the digits. If the sum result to 1 then it is a happy number and if it not results to 1 then if the sum is greater than 10 then it digits are re-extracted and then again added it's square of digits.
JAVA CODE-
import java.util.*;
public class happy
{
int n;
happy()
{
n=0;
}
void getNum(int nx)
{
n=nx;
}
int sum_sq_digits(int d)
{
int sum=0;
while(d>0)
{
sum=sum+((d%10)*(d%10));
d=d/10;
}
int s;int c=0;
while(sum>9)
{
s=sum;
while(s>0)
{
c=c+(s%10);
s=s/10;
}
sum=c;
}
return sum;
}
void isHappy()
{
if(sum_sq_digits(n)==1)
System.out.println("it is a happy number");
else
System.out.println("it is not a happy number");
}
public static void main(String[] arg)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a number");
int x=sc.nextInt();
happy obj=new happy();
obj.getNum(x);
obj.isHappy();
}
}
Output-
enter a number
19
It is a happy number
SIMILAR JAVA CODE-
If you find helpful please share
Comments
Post a Comment