Happy Number in Java

This is a java program for happy number but before that what is ahappy number. A number whose sum of the square of digits is ultimatly equal to 1 is a happy number. By ultimately we mean that starting with any positive number we continue the addition of square of digits till we get a single digit number (0 ~ 9).


For example:
7=7×7
49=4×4+9×9
97= 9×9+7×7
130= 1×1+3×3+0×0
10= 1×1+0×0


Since, 7 is a Happy Number

Code:


import java.util.*;class my
{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int x=n;
int s=n;
do{
n=s;
s=0;
do{
int a=n%10;
s+=a*a;
n/=10;
}
while(n!=0);
}
while(s>9);
if(s==1){
System.out.println("happy");
}
else{
System.out.println("not happy number");
}
}

}

Comments