a java program to check whether the number is a happy number or not.
Answers
Happy number: 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, or it loops endlessly in a cycle which does not include 1.
An unhappy number is a number that is not happy.
The first few unhappy numbers are 2, 3, 4, 5, 6, 8, 9, 11, 12, 14, 15, 16, 17, 18, 20.
Sample Solution:
Java Code:
import java.util. HashSet;
import java.util. Scanner;
import java.util. Set;
public class Example10 {
public static boolean isHappy_number(int num)
{
Set<Integer> unique_num = new HashSet<Integer>();
while (unique_num.add(num))
{
int value = 0;
while (num > 0)
{
value += Math.pow(num % 10, 2);
num /= 10;
}
num = value;
}
return num == 1;
}
public static void main(String[] args)
{
System.out.print("Input a number: ");
int num = new Scanner(System.in).nextInt();
System.out.println(isHappy_number(num) ? "Happy Number" : "Unhappy Number");
}
}
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 happy number or not");
int n=sc.nextInt();
int s=n;
int d=0;
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");
}
}
}