Write a program in java to check whether a number is a happy number or not? (class 9)
Answers
Answer:
import java.util.*;
class happy_number
{
public void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number to check whether it is a magic number or not");
int n=sc.nextInt();
int d=0;
int s=n;
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");
}
}
}
Explanation:
A number is called happy number if the sum of square of its digits until less than 10 are added up to get one as the final result .
Example is :
31
3² + 1² = 9 + 1 = 10
1² + 0² = 1 + 0 = 1
1 is the final result .
Hence 31 is happy .