A happy number is a number in which the eventual sum of the square of the digits of the number is equal to 1.
Example :
28 = 2^2 + 8^2 = 4 + 64 = 68
68 = 6^2 + 8^2 = 36 + 64 = 100
100 = 1 ^2 + 0 ^2 + 0^2 = 1 + 0 + 0 = 1
Hence 28 is a happy number.
Example :
12 = 1^2 + 2^2 = 1 + 4 = 5 Hence 12 is not a happy number.
Design a class Happy to check if a given number is a happy number.
Input: n = 19
Output: True 19 is Happy Number,
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
As we reached to 1, 19 is a Happy Number.
Input: n = 20
Output: False
import java.util.*;
class Happy
{
int n,num;
Scanner sc=new Scanner(System.in);
Happy()
{
n=0;
}
void getnum()
{
System.out.println("Enter the number ");
n= sc.nextInt();
}
int sum_sq_digits(int x)
{
if(x/10==0)
return x*x;
else
{
return (int)Math.pow(x%10,2)+ sum_sq_digits(x/10);
}
}
void ishappy()
{
while((num=sum_sq_digits(n))/10!=0)
{
n=num;
}
if ( num==1)
System.out.println("It is a happy number ");
else
System.out.println("Not a happy number");
}
public static void main(String args[])
{
Happy ob = new Happy();
ob.getnum();
ob.ishappy();
}
}